53 lines
2.1 KiB
C#
53 lines
2.1 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
using UnityEngine.EventSystems;
|
||
using UnityEngine.UI;
|
||
|
||
namespace Ichni.UI
|
||
{
|
||
public class ModifyValueSlider : MonoBehaviour, IPointerClickHandler, IDragHandler
|
||
{
|
||
public ValueModifier valueModifier;
|
||
public RectTransform sliderBackground;
|
||
|
||
public void OnPointerClick(PointerEventData eventData)
|
||
{
|
||
valueModifier.SetValue(valueModifier.GetNearestValue(GetPercentage(eventData.position)));
|
||
}
|
||
|
||
public void OnDrag(PointerEventData eventData)
|
||
{
|
||
valueModifier.SetValue(valueModifier.GetNearestValue(GetPercentage(eventData.position)));
|
||
}
|
||
|
||
private float GetPercentage(Vector2 inputPosition)
|
||
{
|
||
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(sliderBackground, inputPosition, Camera.main, out Vector2 localCursor))
|
||
{
|
||
// 4. 计算百分比
|
||
// localCursor.x 是相对于RectTransform轴心(Pivot)的x坐标
|
||
// 我们需要将其转换为从左边界(0%)到右边界(100%)的百分比
|
||
|
||
// 获取RectTransform的宽度
|
||
float width = sliderBackground.rect.width;
|
||
|
||
// 将相对于轴心的坐标转换为相对于左边界的坐标
|
||
// localCursor.x + rectTransform.pivot.x * width
|
||
// 例如:如果pivot在中心(0.5),localCursor.x的范围是 -width/2 到 +width/2
|
||
// 加上 pivot.x * width (即 0.5 * width) 后,范围就变为 0 到 width
|
||
float distanceFromLeft = localCursor.x + sliderBackground.pivot.x * width;
|
||
|
||
// 计算百分比 (0.0到1.0之间)
|
||
float percentage = distanceFromLeft / width;
|
||
|
||
// 使用Mathf.Clamp01确保结果在0和1之间,防止点击到UI外部一点点时出现误差
|
||
percentage = Mathf.Clamp01(percentage);
|
||
|
||
return percentage;
|
||
}
|
||
|
||
return 0f;
|
||
}
|
||
}
|
||
} |