[C#] 页面拖拽效果 →→→→→进入此内容的聊天室

来自 , 2020-03-16, 写在 C#, 查看 136 次.
URL http://www.code666.cn/view/b096577e
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.EventSystems;
  4. using UnityEngine.UI;
  5. //需要继承IBeginDragHandler,IEndDragHandler这两个接口
  6. public class LevelButtonScrollRect : MonoBehaviour ,IBeginDragHandler,IEndDragHandler
  7. {
  8.     //ScrollRect滑动组件
  9.     private ScrollRect scrollRect;
  10.     //鼠标释放时组件滑动的速度
  11.     public float smoothing = 4;
  12.     //4个页面的位置节点
  13.     private float[] pageArray=new float[]{ 0,0.333f,0.666f,1 };
  14.     //toggle组件,用来页面和页面按钮的同步,需在对象物体赋值
  15.     public Toggle[] toggleArray;
  16.     //用来存储 推算出来 需停靠页面 的值
  17.     private float targetHorizontalPosition=0;
  18.     //判断是否处于拖拽状态
  19.     private bool isDraging = false;
  20.         void Start ()
  21.         {
  22.             scrollRect = GetComponent<ScrollRect>();
  23.         }
  24.         void Update ()
  25.         {
  26.         if(isDraging)  //Mathf.Lerp让物体平衡滑动
  27.                 scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition,
  28.                     targetHorizontalPosition, Time.deltaTime*smoothing);
  29.         }
  30.     public void OnBeginDrag(PointerEventData eventData) //处于拖拽状态
  31.     {
  32.         isDraging = false;
  33.     }
  34.  
  35.     public void OnEndDrag(PointerEventData eventData)  //拖拽结束
  36.     {
  37.         isDraging = true;
  38.         float posX = scrollRect.horizontalNormalizedPosition;
  39.         int index = 0;
  40.         float offset = Mathf.Abs(pageArray[index] - posX);
  41.         for (int i = 1; i < pageArray.Length; i++)
  42.         {
  43.             float offsetTemp = Mathf.Abs(pageArray[i] - posX);
  44.             if (offsetTemp < offset)
  45.             {
  46.                 index = i;
  47.                 offset = offsetTemp;
  48.             }
  49.         }
  50.         targetHorizontalPosition = pageArray[index];
  51.         toggleArray[index].isOn = true;
  52.         //scrollRect.horizontalNormalizedPosition = pageArray[index];
  53.     }
  54.     //4个页面,4个调用方法
  55.     public void MoveToPage1(bool isOn) {
  56.         if (isOn)
  57.         {
  58.             targetHorizontalPosition = pageArray[0];
  59.         }
  60.     }
  61.     public void MoveToPage2(bool isOn) {
  62.         if (isOn) {
  63.             targetHorizontalPosition = pageArray[1];
  64.         }
  65.  
  66.     }
  67.     public void MoveToPage3(bool isOn) {
  68.         if (isOn)
  69.         {
  70.             targetHorizontalPosition = pageArray[2];
  71.         }
  72.  
  73.     }
  74.     public void MoveToPage4(bool isOn) {
  75.  
  76.         if (isOn)
  77.         {
  78.             targetHorizontalPosition = pageArray[3];
  79.         }
  80.     }
  81. }

回复 "页面拖拽效果"

这儿你可以回复上面这条便签

captcha