using System; using EasingCore; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace TyphoonUI { public class Scroller : UIBehaviour, IPointerUpHandler, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler, IScrollHandler { [SerializeField] RectTransform viewport = default; // 视口大小 public float ViewportSize => scrollDirection == ScrollDirection.Horizontal ? viewport.rect.size.x : viewport.rect.size.y; //视口高度 public float ViewportHeight => viewport.rect.size.y; //视口宽度 public float ViewportWidth => viewport.rect.size.x; //视窗大小 public RectTransform ViewPort => viewport; [SerializeField] ScrollDirection scrollDirection = ScrollDirection.Vertical; // 滚动方向 public ScrollDirection ScrollDirection => scrollDirection; [SerializeField] MovementType movementType = MovementType.Elastic; // 移动方式 public MovementType MovementType { get => movementType; set => movementType = value; } [SerializeField] float elasticity = 0.1f; // 弹性量 public float Elasticity { get => elasticity; set => elasticity = value; } [SerializeField] float sensitivity = 1f; // 滚动灵敏度 public float ScrollSensitivity { get => sensitivity; set => sensitivity = value; } [SerializeField] bool inertia = true; // 惯性 public bool Inertia { get => inertia; set => inertia = value; } [SerializeField] float decelerationRate = 0.03f; // 减速率 public float DecelerationRate { get => decelerationRate; set => decelerationRate = value; } [SerializeField] Snap snap = new Snap { Enable = false, VelocityThreshold = 10f, Duration = 0.3f, Easing = Ease.OutBounce }; // 开启吸附 public bool SnapEnabled { get => snap.Enable; set => snap.Enable = value; } [SerializeField] bool draggable = true; // 拖拽输入开关 public bool Draggable { get => draggable; set => draggable = value; } [SerializeField] Scrollbar scrollbar = default; // 滚动条组件 public Scrollbar Scrollbar => scrollbar; // 当前位置 public float Position { get => currentPosition; set { autoScrollState.Reset(); velocity = 0f; dragging = false; UpdatePosition(value); } } readonly AutoScrollState autoScrollState = new AutoScrollState(); Action onValueChanged; Action onSelectionChanged; // private Func calculatePositionFunc; //计算索引坐标 private Func _calculateSnapPositionFunc; //计算吸附坐标 private Action _onSnapStart; //吸附开始 private Action _onSnapEnd; //吸附结束 Vector2 beginDragPointerPosition; float scrollStartPosition; float prevPosition; float currentPosition = 0f; Vector2 scrollRange = Vector2.zero; //滚动范围 int dataCount; //数据数量 bool hold; bool scrolling; bool dragging; float velocity; private float scrollPositionMin => scrollRange.x; //滚动坐标最小值 private float scrollPositionMax => scrollRange.y; //滚动坐标最大值 private float scrollLength => scrollPositionMax - scrollPositionMin; //滚动长度 [Serializable] class Snap { public bool Enable; public float VelocityThreshold; public float Duration; public Ease Easing; } static readonly EasingFunction DefaultEasingFunction = Easing.Get(Ease.OutCubic); class AutoScrollState { public bool Enable; public bool Elastic; public float Duration; public EasingFunction EasingFunction; public float StartTime; public float EndPosition; public Action OnComplete; public void Reset() { Enable = false; Elastic = false; Duration = 0f; StartTime = 0f; EasingFunction = DefaultEasingFunction; EndPosition = 0f; OnComplete = null; } public void Complete() { OnComplete?.Invoke(); Reset(); } } protected override void Start() { base.Start(); if (scrollbar) { scrollbar.onValueChanged.AddListener(x => UpdatePosition(x * scrollLength, false)); } } // 位置变化触发时触发 public void OnValueChanged(Action callback) => onValueChanged = callback; // // 选中的元素发生变化时触发 // public void OnSelectionChanged(Action callback) => onSelectionChanged = callback; // //绑定坐标计算代理 // public void SetCalculatePositionFunc(Func func) => calculatePositionFunc = func; public void SetCalculateSnapPositionFunc(Func func) => _calculateSnapPositionFunc = func; public void SetSnapFunc(Action onSnapStart, Action onSnapEnd) { _onSnapStart = onSnapStart; _onSnapEnd = onSnapEnd; } //重建滚动窗范围 public void Rebuild(Vector2 scrollRange, int dataCount) { this.scrollRange = scrollRange; this.dataCount = dataCount; if (scrollbar != null) { var barLength = scrollDirection == ScrollDirection.Vertical ? viewport.rect.size.y : viewport.rect.size.x; var totalLength = this.scrollRange.y + barLength; scrollbar.size = Mathf.Clamp01(Mathf.InverseLerp(0, totalLength, barLength)); } } //滚动到指定位置(默认Ease) public void ScrollTo(float position, float duration, Action onComplete = null) => ScrollTo(position, duration, Ease.OutCubic, onComplete); //滚动到指定位置(自定义Ease) public void ScrollTo(float position, float duration, Ease easing, Action onComplete = null) => ScrollTo(position, duration, Easing.Get(easing), onComplete); //滚动到指定位置(自定义Ease 代理) public void ScrollTo(float position, float duration, EasingFunction easingFunction, Action onComplete = null) { Action complete = () => { _onSnapEnd?.Invoke(Position); onComplete?.Invoke(); }; if (duration <= 0f) { Position = Mathf.Clamp(position, scrollPositionMin, scrollPositionMax); _onSnapStart?.Invoke(position); complete?.Invoke(); return; } _onSnapStart?.Invoke(position); autoScrollState.Reset(); autoScrollState.Enable = true; autoScrollState.Duration = duration; autoScrollState.EasingFunction = easingFunction ?? DefaultEasingFunction; autoScrollState.StartTime = Time.unscaledTime; autoScrollState.EndPosition = currentPosition + CalculateMovementAmount(currentPosition, position); autoScrollState.OnComplete = complete; velocity = 0f; scrollStartPosition = currentPosition; //TODO// // UpdateSelection(Mathf.RoundToInt(CircularPosition(autoScrollState.EndPosition, totalCount))); } //转到指定滚动坐标位置 public void JumpToScrollPosition(float pos) { Position = pos; } public MovementDirection GetMovementDirection(int sourceIndex, int destIndex) { var movementAmount = CalculateMovementAmount(sourceIndex, destIndex); return scrollDirection == ScrollDirection.Horizontal ? movementAmount > 0 ? MovementDirection.Left : MovementDirection.Right : movementAmount > 0 ? MovementDirection.Up : MovementDirection.Down; } void IPointerDownHandler.OnPointerDown(PointerEventData eventData) { if (!draggable || eventData.button != PointerEventData.InputButton.Left) { return; } hold = true; velocity = 0f; autoScrollState.Reset(); } void IPointerUpHandler.OnPointerUp(PointerEventData eventData) { if (!draggable || eventData.button != PointerEventData.InputButton.Left) { return; } if (hold && snap.Enable) { //吸附到最近目标位置 if (_calculateSnapPositionFunc != null) { var snapResult = _calculateSnapPositionFunc.Invoke(currentPosition); ScrollTo(snapResult.SnapPos, snap.Duration, snap.Easing); } } hold = false; } void IScrollHandler.OnScroll(PointerEventData eventData) { if (!draggable) { return; } var delta = eventData.scrollDelta; // Down is positive for scroll events, while in UI system up is positive. delta.y *= -1; var scrollDelta = scrollDirection == ScrollDirection.Horizontal ? Mathf.Abs(delta.y) > Mathf.Abs(delta.x) ? delta.y : delta.x : Mathf.Abs(delta.x) > Mathf.Abs(delta.y) ? delta.x : delta.y; if (eventData.IsScrolling()) { scrolling = true; } var position = currentPosition + scrollDelta / ViewportSize * sensitivity * ViewportSize; if (movementType == MovementType.Clamped) { position += CalculateOffset(position); } if (autoScrollState.Enable) { autoScrollState.Reset(); } UpdatePosition(position); } void IBeginDragHandler.OnBeginDrag(PointerEventData eventData) { if (!draggable || eventData.button != PointerEventData.InputButton.Left) { return; } hold = false; RectTransformUtility.ScreenPointToLocalPointInRectangle( viewport, eventData.position, eventData.pressEventCamera, out beginDragPointerPosition); scrollStartPosition = currentPosition; dragging = true; autoScrollState.Reset(); } void IDragHandler.OnDrag(PointerEventData eventData) { if (!draggable || eventData.button != PointerEventData.InputButton.Left || !dragging) { return; } if (!RectTransformUtility.ScreenPointToLocalPointInRectangle( viewport, eventData.position, eventData.pressEventCamera, out var dragPointerPosition)) { return; } var pointerDelta = dragPointerPosition - beginDragPointerPosition; var position = (scrollDirection == ScrollDirection.Horizontal ? -pointerDelta.x : pointerDelta.y) / ViewportSize * sensitivity * ViewportSize + scrollStartPosition; var offset = CalculateOffset(position); position += offset; if (movementType == MovementType.Elastic) { if (offset != 0f) { position -= RubberDelta(offset, sensitivity * ViewportSize); } } UpdatePosition(position); } void IEndDragHandler.OnEndDrag(PointerEventData eventData) { if (!draggable || eventData.button != PointerEventData.InputButton.Left) { return; } dragging = false; } float CalculateOffset(float position) { if (movementType == MovementType.Unrestricted) { return 0f; } if (position < scrollPositionMin) { return -position; } if (position > scrollPositionMax) { return scrollPositionMax - position; } return 0f; } void UpdatePosition(float position, bool updateScrollbar = true) { onValueChanged?.Invoke(currentPosition = position); if (scrollbar && updateScrollbar) { scrollbar.value = Mathf.Clamp01(position / Mathf.Max(scrollLength, 1e-4f)); } } void UpdateSelection(int index) => onSelectionChanged?.Invoke(index); float RubberDelta(float overStretching, float viewSize) => (1 - 1 / (Mathf.Abs(overStretching) * 0.55f / viewSize + 1)) * viewSize * Mathf.Sign(overStretching); void Update() { var deltaTime = Time.unscaledDeltaTime; var offset = CalculateOffset(currentPosition); if (autoScrollState.Enable) { var position = 0f; if (autoScrollState.Elastic) { position = Mathf.SmoothDamp(currentPosition, currentPosition + offset, ref velocity, elasticity, Mathf.Infinity, deltaTime); if (Mathf.Abs(velocity) < 0.01f) { position = Mathf.Clamp(position, scrollPositionMin, scrollPositionMax); velocity = 0f; autoScrollState.Complete(); } } else { var alpha = Mathf.Clamp01((Time.unscaledTime - autoScrollState.StartTime) / Mathf.Max(autoScrollState.Duration, float.Epsilon)); position = Mathf.LerpUnclamped(scrollStartPosition, autoScrollState.EndPosition, autoScrollState.EasingFunction(alpha)); if (Mathf.Approximately(alpha, 1f)) { autoScrollState.Complete(); } } UpdatePosition(position); } else if (!(dragging || scrolling) && (!Mathf.Approximately(offset, 0f) || !Mathf.Approximately(velocity, 0f))) { var position = currentPosition; if (movementType == MovementType.Elastic && !Mathf.Approximately(offset, 0f)) { // Debug.Log("1111"); autoScrollState.Reset(); autoScrollState.Enable = true; autoScrollState.Elastic = true; //吸附到临近目标 if (snap.Enable) { //吸附到临近目标 if (_calculateSnapPositionFunc != null) { var snapResult = _calculateSnapPositionFunc.Invoke(currentPosition); // Debug.Log($"吸附:{pos}"); ScrollTo(snapResult.SnapPos, snap.Duration, snap.Easing); } } } else if (inertia) { // Debug.Log("222"); velocity *= Mathf.Pow(decelerationRate, deltaTime); if (Mathf.Abs(velocity) < 0.001f) { velocity = 0f; } position += velocity * deltaTime; if (snap.Enable && Mathf.Abs(velocity) < snap.VelocityThreshold) { //吸附到临近目标 if (_calculateSnapPositionFunc != null) { var snapResult = _calculateSnapPositionFunc.Invoke(currentPosition); // Debug.Log($"吸附:{pos}"); ScrollTo(snapResult.SnapPos, snap.Duration, snap.Easing); } } } else { // Debug.Log("3333"); velocity = 0f; } if (!Mathf.Approximately(velocity, 0f)) { if (movementType == MovementType.Clamped) { offset = CalculateOffset(position); position += offset; if (Mathf.Approximately(position, scrollPositionMin) || Mathf.Approximately(position, scrollPositionMax)) { velocity = 0f; //TODO// // UpdateSelection(Mathf.RoundToInt(position)); } } // Debug.Log("4444"); UpdatePosition(position); } } if (!autoScrollState.Enable && (dragging || scrolling) && inertia) { var newVelocity = (currentPosition - prevPosition) / deltaTime; velocity = Mathf.Lerp(velocity, newVelocity, deltaTime * 10f); } prevPosition = currentPosition; scrolling = false; } //计算移动量 float CalculateMovementAmount(float sourcePosition, float destPosition) { if (movementType != MovementType.Unrestricted) { return Mathf.Clamp(destPosition, scrollPositionMin, scrollPositionMax) - sourcePosition; } return destPosition - sourcePosition; } } }