2016-10-04 13:45:21
1 using UnityEngine; 2 using System.Collections; 3 using UnityEngine.EventSystems; 4 using System; 5 using UnityEngine.UI; 6 public class LevelButtonScrollRect : MonoBehaviour, IBeginDragHandler, IEndDragHandler 7 { 8 private ScrollRect scrollRect; 9 private float[] pageArray = new float[] { 0, 0.333f, 0.666f, 1 }; 10 public Toggle[] ToggleArray; 11 private float speed = 5f; 12 private float targetHorizontalPosition = 0f; 13 private bool isDraging = false; 14 void Start() 15 { 16 scrollRect = transform.GetComponent<ScrollRect>(); 17 } 18 19 void Update() 20 { 21 if (!isDraging) 22 { 23 scrollRect.horizontalNormalizedPosition = Mathf.Lerp(scrollRect.horizontalNormalizedPosition, 24 targetHorizontalPosition, Time.deltaTime * speed); 25 } 26 27 } 28 public void OnBeginDrag(PointerEventData eventData) 29 { 30 isDraging = true; 31 } 32 public void OnEndDrag(PointerEventData eventData) 33 { 34 isDraging = false; 35 // 得到 水平滑动的 值 (0-1) 36 float posX = scrollRect.horizontalNormalizedPosition; 37 int index = 0; 38 float offset = Mathf.Abs(posX - pageArray[index]); 39 // 与 前后比较 距离最短 40 for (int i = 1; i < pageArray.Length; i++) 41 { 42 // 距离 最短 43 float offsetTemp = Mathf.Abs(posX - pageArray[i]); 44 if (offset > offsetTemp) 45 { 46 index = i; 47 offset = offsetTemp; 48 } 49 } 50 targetHorizontalPosition = pageArray[index]; 51 ToggleArray[index].isOn = true; 52 } 53 }
时间: 2024-10-13 05:06:55