Unity3D实现页面的滑动切换功能

效果展示

Unity3D实现页面的滑动切换 效果

文章目录


前言

``

好记性不如烂笔头!

一、先上代码

/**********************************************************************
 文件信息
 文件名(File Name):                PageView.cs
 作者(Author):                      TianWenQuan
 创建时间(CreateTime):             #CREATETIME#
 **********************************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System;
namespace Twq
{
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    using UnityEngine.EventSystems;
    using System;
    using UnityEngine.Events;
    using System.Reflection;
    //using RenderHeads.Media.AVProVideo.Demos;
    //using RenderHeads.Media.AVProVideo;

    /// <summary>
    /// 滑动页面效果
    /// </summary>
    public class PageView : MonoBehaviour, IBeginDragHandler, IEndDragHandler
    {
        public static PageView pageViewIn;
        private ScrollRect rect;
        private float targethorizontal = 0;
        private List<float> posList = new List<float>();//存四张图片的位置(0, 0.333, 0.666, 1) 
        private bool isDrag = true;
        private float startTime = 0;
        private float startDragHorizontal;
        private int curIndex = 0;

        public float speed = 2;      //滑动速度  
        public float sensitivity = 0;
        public Text curPage;

        public Transform Content;
       // public GameObject MediaPlayerUI_;
        //public MediaPlayer MediaPlayer_;

        public Transform PageList;//页面List
        public Button LeftButton;
        public Button RightButton;
        void Awake()
        {
            pageViewIn = this;
          
            LeftButton.onClick.AddListener(OnLeftButton);
            RightButton.onClick.AddListener(OnRightButton);
            for (int i = 0; i < PageList.childCount; i++)
            {
                int x = i;
                PageList.GetChild(x).transform.GetComponent<Toggle>().onValueChanged.AddListener((b) => {
                    if (b)
                    {
                        pageTo(x);
                    }
                });
            }


            rect = GetComponent<ScrollRect>();
            Debug.Log("rect.content.rect.width="+ rect.content.rect.width);
            Debug.Log(" GetComponent<RectTransform>().rect.width=" + GetComponent<RectTransform>().rect.width);
            float horizontalLength = rect.content.rect.width - GetComponent<RectTransform>().rect.width;
            Debug.Log(horizontalLength);
            var _rectWidth = GetComponent<RectTransform>().rect.width;
            Debug.Log(_rectWidth);
            Debug.Log(rect.content.transform.childCount);
            for (int i = 0; i < rect.content.transform.childCount; i++)
            {
                Debug.Log("---"+ (_rectWidth * i / horizontalLength).ToString());
                posList.Add(_rectWidth * i / horizontalLength);   //存四张图片的位置
            }
            curIndex = 0;
            curPage.text = String.Format("当前页码:0");
            Content.parent.parent.GetComponent<ScrollRect>().normalizedPosition = new Vector2(0, 1);
            LayoutRebuilder.ForceRebuildLayoutImmediate(Content.GetComponent<RectTransform>());
        }
       

        void Update()
        {
            if (!isDrag)
            {
                startTime += Time.deltaTime;
                float t = startTime * speed;
                //加速滑动效果
                rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, t);
                //缓慢匀速滑动效果
                // rect.horizontalNormalizedPosition = Mathf.Lerp(rect.horizontalNormalizedPosition, targethorizontal, Time.deltaTime * speed);

            }
        }
        /// <summary>
        /// 开始拖拽
        /// </summary>
        /// <param name="eventData"></param>
        public void OnBeginDrag(PointerEventData eventData)
        {
            Debug.Log("----开始拖动");
            isDrag = true;
            //开始拖动
            startDragHorizontal = rect.horizontalNormalizedPosition;  //horizontalNormalizedPosition这个参数是scrollRect滑动期间变化的x坐标值,在(0, 1)之间
        }

        /// <summary>
        /// 拖拽结束
        /// </summary>
        /// <param name="eventData"></param>
        public void OnEndDrag(PointerEventData eventData)
        {
            Debug.Log("拖动结束");
            float posX = rect.horizontalNormalizedPosition;
            int index = 0;
            float offset = Mathf.Abs(posList[index] - posX);  //计算当前位置与第一页的偏移量,初始化offect
            for (int i = 1; i < posList.Count; i++)
            {    //遍历页签,选取当前x位置和每页偏移量最小的那个页面
                float temp = Mathf.Abs(posList[i] - posX);
                if (temp < offset)
                {
                    index = i;
                    offset = temp;
                }
            }
            curIndex = index;
            targethorizontal = posList[curIndex]; //设置当前坐标,更新函数进行插值  
            isDrag = false;
            startTime = 0;
            curPage.text = String.Format("当前页码:{0}", curIndex.ToString());
            PageList.GetChild(curIndex + 1).transform.GetComponent<Toggle>().isOn = true;
        }
        
        /// <summary>
        /// 左边下一页 按钮
        /// </summary>
        public void OnLeftButton()
        {
            // Debug.Log("curIndex" + curIndex + "   posList.Count=" + PageList.childCount);
            if (curIndex <= 0)
            {
                 Debug.Log("左边不能点击了");
                return;
            }
            curIndex -= 1;
            PageList.GetChild(curIndex).transform.GetComponent<Toggle>().isOn = true;
            pageTo(curIndex);


        }
        /// <summary>
        /// 右边下一页 按钮
        /// </summary>
        public void OnRightButton()
        {
            // Debug.Log("curIndex" + curIndex + "  PageList=" + PageList.childCount);
            if (curIndex >= PageList.childCount - 1)
            {
                 Debug.Log("右边不能点击了");
                return;
            }
            curIndex += 1;
            PageList.GetChild(curIndex).transform.GetComponent<Toggle>().isOn = true;
            pageTo(curIndex);
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="index"></param>
        public void pageTo(int index)
        {
            if (index < 0) { return; }
            // Debug.Log("pageTo......index="+ index);
            curIndex = index;
            targethorizontal = posList[curIndex]; //设置当前坐标,更新函数进行插值  
            isDrag = false;
            startTime = 0;
            curPage.text = String.Format("当前页码:{0}", curIndex.ToString());
          //  MediaPlayer_.Stop();
            //MediaPlayerUI_.SetActive(false);
            if (index==1)
            {
             //   MediaPlayerUI_.SetActive(true);
            }
        }
    }
}

二、创建UI

1.创建Scroll View如下图,并挂载该脚本:

2.Content下创建几个Itme

对齐方式,可以根据需求使用以下:
!

因为代码里需要使用到Content的宽,让其自动填充宽度。最后删除该组件Content Size Fitte(不删除,可以自己尝试下,会影响我们要的翻动效果)

Content的对齐位置如下:

创建左右按钮和12345翻页按钮,就不仔细写了,都是调用脚本里的方法而已。

示例Dome:https://download.csdn.net/download/qq_37524903/88499409?spm=1001.2014.3001.5501

总结

好记性不如烂笔头

相关推荐
奔跑的犀牛先生3 小时前
unity学习26:用Input接口去监测: 鼠标,键盘,虚拟轴,虚拟按键
unity
Dr.勿忘13 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
存储服务专家StorageExpert13 小时前
答疑解惑:如何监控EMC unity存储系统磁盘重构rebuild进度
运维·unity·存储维护·emc存储
追逐梦想永不停20 小时前
Unity实现按键设置功能代码
unity
我命由我123451 天前
游戏引擎 Unity - Unity 下载与安装
c语言·开发语言·c++·后端·unity·c#·游戏引擎
车载诊断技术1 天前
车载软件架构 --- 基于AUTOSAR软件架构的ECU开发流程小白篇
网络·unity·架构·汽车·电子电器框架·车载充电器(obc)
我命由我123451 天前
游戏引擎 Unity - Unity 启动(下载 Unity Editor、生成 Unity Personal Edition 许可证)
c语言·c++·后端·unity·c#·游戏引擎·ue4
我命由我123452 天前
游戏开发领域 - 游戏引擎 UE 与 Unity
开发语言·c++·unity·c#·游戏引擎·unreal engine·unreal engine 4
一个一定要撑住的学习者2 天前
Day29(补)-【AI思考】-精准突围策略——从“时间贫困“到“效率自由“的逆袭方案
人工智能·unity·游戏引擎
浅陌sss3 天前
Unity 粒子特效在UI中使用裁剪效果
ui·unity·游戏引擎