LerpSlider.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI;
  6. public class LerpSlider : UnityEngine.UI.Slider, IPointerDownHandler
  7. {
  8. private float lerpDuration = 0.08f; // 过渡时间
  9. private float targetValue;
  10. private bool isLerping;
  11. protected override void Update()
  12. {
  13. base.Update();
  14. if (isLerping)
  15. {
  16. // 平滑过渡到目标值
  17. value = Mathf.Lerp(value, targetValue, Time.deltaTime / lerpDuration);
  18. // 检查是否接近目标值,结束过渡
  19. if (Mathf.Abs(value - targetValue) < 0.01f)
  20. {
  21. value = targetValue;
  22. isLerping = false;
  23. }
  24. }
  25. }
  26. public void OnPointerDown(PointerEventData eventData)
  27. {
  28. // 计算点击位置的值
  29. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  30. GetComponent<RectTransform>(), eventData.position, eventData.pressEventCamera, out var localPoint);
  31. // 计算滑块的点击位置对应的值
  32. float normalizedValue = Mathf.InverseLerp(
  33. GetComponent<RectTransform>().rect.xMin,
  34. GetComponent<RectTransform>().rect.xMax,
  35. localPoint.x
  36. );
  37. targetValue = Mathf.Clamp01(normalizedValue); // 确保值在0到1之间
  38. isLerping = true;
  39. }
  40. }