ValidateJigsawDragBar.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. using UnityEngine.EventSystems;
  6. namespace JCUnityLib.UI
  7. {
  8. public class ValidateJigsawDragBar : MonoBehaviour, IDragHandler, IEndDragHandler, IBeginDragHandler
  9. {
  10. RectTransform _self;
  11. RectTransform _parent;
  12. float _minX { get => 0; }
  13. float _maxX { get => _parent.rect.width - _self.rect.width; }
  14. bool _draged;
  15. float _value;
  16. public UnityAction<float> onDrag;
  17. public UnityAction<float> onEndDrag;
  18. void Awake()
  19. {
  20. _self = transform as RectTransform;
  21. _parent = transform.parent as RectTransform;
  22. }
  23. void Update()
  24. {
  25. if (!_draged && _self.anchoredPosition.x > 0)
  26. {
  27. _self.anchoredPosition += Vector2.left * 2000 * Time.deltaTime;
  28. if (_self.anchoredPosition.x < 0) _self.anchoredPosition = Vector3.zero;
  29. UpdateValue();
  30. onDrag?.Invoke(_value);
  31. }
  32. }
  33. void UpdateValue()
  34. {
  35. _value = _self.anchoredPosition.x / (_maxX - _minX);
  36. }
  37. void MoveSelf(Vector3 v3)
  38. {
  39. v3.y = 0;
  40. _self.Translate(v3, Space.Self);
  41. if (_self.anchoredPosition.x > _maxX)
  42. {
  43. v3.x = _maxX;
  44. _self.anchoredPosition = v3;
  45. }
  46. else if (_self.anchoredPosition.x < 0)
  47. {
  48. v3.x = _minX;
  49. _self.anchoredPosition = v3;
  50. }
  51. }
  52. public void OnDrag(PointerEventData eventData)
  53. {
  54. MoveSelf(eventData.delta);
  55. UpdateValue();
  56. onDrag?.Invoke(_value);
  57. }
  58. public void OnEndDrag(PointerEventData eventData)
  59. {
  60. _draged = false;
  61. onEndDrag?.Invoke(_value);
  62. }
  63. public void OnBeginDrag(PointerEventData eventData)
  64. {
  65. _draged = true;
  66. }
  67. }
  68. }