UGUIJoyStickBase.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.EventSystems;
  6. public class UGUIJoyStickBase : UIBase, IDragHandler, IEndDragHandler, IBeginDragHandler
  7. {
  8. protected float mRadius;
  9. public RectTransform content;
  10. public UGUIJoyStickHandle onJoyStick;
  11. protected bool canMove = true;
  12. void Start()
  13. {
  14. MyStart();
  15. }
  16. virtual public void MyStart()
  17. {
  18. //计算摇杆块的半径
  19. mRadius = ((transform as RectTransform).sizeDelta.x - content.sizeDelta.x) * 0.5f;
  20. }
  21. virtual public void OnBeginDrag(PointerEventData eventData)
  22. {
  23. canMove = true;
  24. }
  25. virtual public void OnDrag(PointerEventData eventData)
  26. {
  27. Vector3 contentPostion = content.anchoredPosition + eventData.delta;
  28. if (contentPostion.magnitude > mRadius)
  29. {
  30. contentPostion = contentPostion.normalized * mRadius;
  31. }
  32. content.anchoredPosition3D = contentPostion;
  33. }
  34. virtual public void OnEndDrag(PointerEventData eventData)
  35. {
  36. content.anchoredPosition3D = Vector3.zero;
  37. onJoyStick(Vector3.zero);
  38. }
  39. protected Vector3 GetDir()
  40. {
  41. Vector3 dir = new Vector3(content.anchoredPosition3D.x, 0, content.anchoredPosition3D.y);
  42. dir /= mRadius;
  43. return dir;
  44. }
  45. void Update()
  46. {
  47. if (onJoyStick != null)
  48. {
  49. try
  50. {
  51. if (GetDir() != Vector3.zero && canMove)
  52. {
  53. onJoyStick(GetDir());
  54. }
  55. }
  56. catch (Exception e)
  57. {
  58. Debug.LogError(e.ToString());
  59. }
  60. }
  61. }
  62. public void ReHomePos()
  63. {
  64. canMove = false;
  65. content.anchoredPosition3D = Vector3.zero;
  66. onJoyStick(Vector3.zero);
  67. }
  68. }