using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace MuHua {
///
/// 滑块 - 垂直
///
public class UISliderV : ModuleUIPanel, IDisposable {
/// 绑定的画布
public readonly VisualElement canvas;
/// 元素方向
public readonly UIDirection direction;
/// 值改变时
public event Action ValueChanged;
///
/// 方向
///
public enum UIDirection {
FromTopToBottom = 0,
FromBottomToTop = 1,
}
public float value;
public bool isDragger;
public float originalPosition;
public float pointerPosition;
public readonly VisualElement Title;
public readonly VisualElement Container;
public readonly VisualElement Tracker;
public readonly VisualElement Dragger;
public UISliderV(VisualElement element, VisualElement canvas, UIDirection direction = UIDirection.FromTopToBottom) : base(element) {
this.canvas = canvas;
this.direction = direction;
Title = Q("Title");
Container = Q("Container");
Tracker = Q("Tracker");
Dragger = Q("Dragger");
//设置事件
Dragger.RegisterCallback(DraggerDown);
Container.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;
float value1 = Tracker.resolvedStyle.height;
float value2 = Container.resolvedStyle.height - Tracker.resolvedStyle.height;
originalPosition = direction == UIDirection.FromTopToBottom ? value1 : value2;
pointerPosition = Screen.height - UITool.GetMousePosition().y;
}
/// 元素按下
private void ElementDown(PointerDownEvent evt) {
float offset = evt.localPosition.y;
float max = Container.resolvedStyle.height;
float value1 = Mathf.InverseLerp(0, max, offset);
float value2 = Mathf.InverseLerp(max, 0, offset);
float value = direction == UIDirection.FromTopToBottom ? value1 : value2;
UpdateValue(value);
}
/// 鼠标松开或离开
private void DraggerUpOrLeave(EventBase evt) {
isDragger = false;
}
/// 更新状态
public void Update() {
if (!isDragger) { return; }
float differ = Screen.height - UITool.GetMousePosition().y - pointerPosition;
float offset = differ + originalPosition;
float max = Container.resolvedStyle.height;
float value1 = Mathf.InverseLerp(0, max, offset);
float value2 = Mathf.InverseLerp(max, 0, offset);
float value = direction == UIDirection.FromTopToBottom ? value1 : value2;
UpdateValue(value);
}
/// 更新值(0-1)
public void UpdateValue(float obj, bool send = true) {
value = (float)Math.Round(obj, 3);
if (send) { ValueChanged?.Invoke(value); }
Tracker.style.height = Length.Percent(value * 100);
}
}
}