LerpSlider.cs 1.6 KB

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