Unity-ScrollView实现页面翻动效果


游戏关卡需要通过触屏翻动来选择。

实现:

  • 创建panel后在面板下边创建UI-ScrollView,在content下完成当前游戏所需UI。

 

 

 

示例游戏面板:

 

  • 挂载脚本到ScrollVeiw组件下方,代码如下。
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using UnityEngine.UI;
 5 using UnityEngine.EventSystems;
 6 using System;
 7 using DG.Tweening;
 8 
 9 public class SlideScrollView : MonoBehaviour,IBeginDragHandler,IEndDragHandler {
10 
11     private RectTransform contentTrans;
12     private float beginMousePositionX;
13     private float endMousePositionX;
14     private ScrollRect scrollRect;
15 
16     public int cellLength;
17     public int spacing;
18     public int leftOffset;
19     private float moveOneItemLength;
20 
21     private Vector3 currentContentLocalPos;
22 
23     public int totalItemNum;
24     public int currentIndex;
25 
26     private void Awake()
27     {
28         scrollRect = GetComponent<ScrollRect>();
29         contentTrans = scrollRect.content;
30         moveOneItemLength = cellLength + spacing;       //移动一个单元格所需距离
31         currentContentLocalPos = contentTrans.localPosition;    //UI一出现就把content记录下位置做初始值
32         currentIndex = 1;
33     }
34 
35     public void OnEndDrag(PointerEventData eventData)
36     {
37         endMousePositionX = Input.mousePosition.x;      //结束拖拽时也要取得鼠标终止位置
38         float offSetX = 0;          //差值先赋值
39         float moveDistance = 0;     //具体要去移动的距离 当次需要滑动的距离
40         offSetX = beginMousePositionX - endMousePositionX;  
41 
42         if (offSetX > 0)                //差值如果大于0就是 右滑
43         {
44             if (currentIndex >= totalItemNum)       //如果已经滑到最右端了就不能动了
45             {
46                 return;
47             }
48             moveDistance = moveOneItemLength;
49             currentIndex++;
50         }
51         else                            //否则左滑
52         {
53             if (currentIndex <= 1)      //已经滑动到最左端
54             {
55                 return;
56             }
57             moveDistance = moveOneItemLength;
58             currentIndex--;
59         }
60         DOTween.To(() => contentTrans.localPosition, lerpValue => contentTrans.localPosition = lerpValue, currentContentLocalPos + new Vector3(moveDistance,0,0),0.3f).SetEase(Ease.Linear);
61         //想要改变局部坐标                 令当前的局部坐标=计算出来的差值        想要达到:当前存在的位置+当次需要具体移动的位置(上边计算出来的移动距离,y和z不需要移动) 0.5s完成移动 最后是缓动函数
62         currentContentLocalPos += new Vector3(moveDistance, 0, 0);
63     }
64 
65     public void OnBeginDrag(PointerEventData eventData)
66     {
67         beginMousePositionX = Input.mousePosition.x;        //取鼠标起始位置
68     }
69 }

 

 

 

 右滑体验感并不好,调整了单个单元格长度、间隙和左偏移值以后还是毫无变化,代码解释见注释,待修改。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM