using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace MuHua { /// /// 滚动条 - 水平 /// public class UIScrollerH : ModuleUIPanel, UIControl { /// 绑定的画布 public readonly VisualElement canvas; /// 元素方向 public readonly UIDirection direction; /// 值改变时 public event Action ValueChanged; /// /// 方向 /// public enum UIDirection { FromLeftToRight = 0, FromRightToLeft = 1, } public float value; public bool isDragger; public float originalPosition; public float pointerPosition; public readonly VisualElement Dragger; public UIScrollerH(VisualElement element, VisualElement canvas, UIDirection direction = UIDirection.FromLeftToRight) : base(element) { this.canvas = canvas; this.direction = direction; Dragger = Q("Dragger"); element.style.flexDirection = direction == UIDirection.FromLeftToRight ? FlexDirection.Row : FlexDirection.RowReverse; //设置事件 Dragger.RegisterCallback(DraggerDown); element.RegisterCallback(ElementDown); canvas.RegisterCallback(DraggerUpOrLeave); canvas.RegisterCallback(DraggerUpOrLeave); } /// 解绑事件,防止内存泄漏 public void Dispose() { Dragger.UnregisterCallback(DraggerDown); element.UnregisterCallback(ElementDown); canvas.UnregisterCallback(DraggerUpOrLeave); canvas.UnregisterCallback(DraggerUpOrLeave); } /// 拖拽按下 private void DraggerDown(PointerDownEvent evt) { isDragger = true; originalPosition = Dragger.transform.position.x; pointerPosition = UITool.GetMousePosition().x; } /// 元素按下 private void ElementDown(PointerDownEvent evt) { float offset = evt.localPosition.x - Dragger.resolvedStyle.width * 0.5f; float max = element.resolvedStyle.width - Dragger.resolvedStyle.width; float value1 = Mathf.InverseLerp(0, max, offset); float value2 = Mathf.InverseLerp(max, 0, offset); float value = direction == UIDirection.FromLeftToRight ? value1 : value2; UpdateValue(value); } /// 鼠标松开或离开 private void DraggerUpOrLeave(EventBase evt) { isDragger = false; } /// 更新状态 public void Update() { if (!isDragger) { return; } float differ = UITool.GetMousePosition().x - pointerPosition; float offset = differ + originalPosition; offset *= direction == UIDirection.FromLeftToRight ? 1 : -1; float max = element.resolvedStyle.width - Dragger.resolvedStyle.width; float value = Mathf.InverseLerp(0, max, offset); UpdateValue(value); } /// 更新值(0-1) public void UpdateValue(float value, bool send = true) { this.value = value; if (send) { ValueChanged?.Invoke(value); } float max = element.resolvedStyle.width - Dragger.resolvedStyle.width; float position = Mathf.Lerp(0, max, value); position *= direction == UIDirection.FromLeftToRight ? 1 : -1; Dragger.transform.position = new Vector2(position, 0); } } }