优化ScrollRect ,实现自动定位到Item中心
Posted weiqiangwaideshijie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了优化ScrollRect ,实现自动定位到Item中心相关的知识,希望对你有一定的参考价值。
using UnityEngine; using System.Collections; using UnityEngine.UI; using Spine; using Spine.Unity; using System; using Global; using Kernal; using UnityEngine.EventSystems; namespace Controll { public class ItemDetailTip_Scroll : MonoBehaviour, IBeginDragHandler, IEndDragHandler,IDragHandler { [SerializeField] private ScrollRect _scrollRect; [SerializeField] private RectTransform _contentTrans; public float Smoothing = 4f; private float[] _pageArry; private float _targetHorizontalPos = 0; private bool _isDraging = false; [SerializeField] private float _offset = 0.1f; private bool _isDragLeft = true; private float _curHPosx = 0; [SerializeField] private bool _isTest = false; [SerializeField] private Toggle[] _toggleList; public void Init(float width,float[] pageArry,int pos) { _curHPosx = _scrollRect.horizontalNormalizedPosition; _contentTrans.sizeDelta = new Vector2(width, 1080); _pageArry = new float[pageArry.Length]; _pageArry = pageArry; gameObject.SetActive(true); _targetHorizontalPos = _pageArry[pos]; _scrollRect.horizontalNormalizedPosition = _targetHorizontalPos; for(int i=0;i<_toggleList.Length;i++) { if(i<pageArry.Length) { _toggleList[i].gameObject.SetActive(true); }else { _toggleList[i].gameObject.SetActive(false); } } _toggleList[pos].isOn = true; } private void Update() { // Log.Debug(_scrollRect.horizontalNormalizedPosition); if (!_isDraging) { if (_isTest) return; _scrollRect.horizontalNormalizedPosition = Mathf.Lerp(_scrollRect.horizontalNormalizedPosition, _targetHorizontalPos, Time.deltaTime * Smoothing); } } public void OnBeginDrag(PointerEventData eventData) { _isDraging = true; } public void OnDrag(PointerEventData eventData) { if (_scrollRect.horizontalNormalizedPosition>_curHPosx) { _isDragLeft = true; }else { _isDragLeft = false; } _curHPosx = _scrollRect.horizontalNormalizedPosition; } public void OnEndDrag(PointerEventData eventData) { _isDraging = false; float posX = _scrollRect.horizontalNormalizedPosition; int index = 0; float offset = Mathf.Abs(_pageArry[index]-posX); for (int i = 0; i < _pageArry.Length; i++) { float offsetTmp = Mathf.Abs(_pageArry[i] - posX); if(_isDragLeft) { _offset = Mathf.Abs(_offset); }else { _offset = -Mathf.Abs(_offset); } if(offsetTmp<offset+ _offset) { index = i; offset = offsetTmp; } } _targetHorizontalPos = _pageArry[index]; _toggleList[index].isOn = true; } } }
效果:
以上是关于优化ScrollRect ,实现自动定位到Item中心的主要内容,如果未能解决你的问题,请参考以下文章
如何优化UGUI的ScrollRect-Unity-VR开发网
[Unity学习]使用ScrollRect实现自动滚动到底部显示实时消息,并在拖动的时候取消自动滚动,再次手动滑到底部,又继续自动滚动
[Unity学习]使用ScrollRect实现自动滚动到底部显示实时消息,并在拖动的时候取消自动滚动,再次手动滑到底部,又继续自动滚动
[Unity学习]使用ScrollRect实现自动滚动到底部显示实时消息,并在拖动的时候取消自动滚动,再次手动滑到底部,又继续自动滚动