UGUIJoyStick.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using UnityEngine.EventSystems;
  5. using System;
  6. public class UGUIJoyStick : UIBase, IDragHandler, IEndDragHandler,IBeginDragHandler
  7. {
  8. protected float mRadius;
  9. public RectTransform content;
  10. public UGUIJoyStickHandle onJoyStick;
  11. public bool canMove = true;
  12. //当前分辨率,与UImanager上的标准分辨率之间的换算比
  13. public float conversionX;
  14. public float conversionY;
  15. void Start()
  16. {
  17. //计算摇杆块的半径
  18. mRadius = ((transform as RectTransform).sizeDelta.x-content.sizeDelta.x) * 0.5f;
  19. Vector2 referenceResolution = UIManager.UIManagerGo.GetComponent<CanvasScaler>().referenceResolution;
  20. conversionX = referenceResolution.x / Screen.width ;
  21. conversionY = referenceResolution.y/Screen.height ;
  22. }
  23. public void OnBeginDrag(PointerEventData eventData)
  24. {
  25. canMove = true;
  26. }
  27. Vector2 centerDelta = new Vector2(0, 0);
  28. public void OnDrag(PointerEventData eventData)
  29. {
  30. centerDelta.x = eventData.delta.x * conversionX;
  31. centerDelta.y = eventData.delta.y * conversionY;
  32. Vector3 contentPostion = content.anchoredPosition + centerDelta;
  33. if (contentPostion.magnitude > mRadius)
  34. {
  35. contentPostion = contentPostion.normalized * mRadius;
  36. }
  37. content.anchoredPosition3D = contentPostion;
  38. //onJoyStick(GetDir());
  39. }
  40. public void OnEndDrag(PointerEventData eventData)
  41. {
  42. canMove = false;
  43. content.anchoredPosition3D = Vector3.zero;
  44. //onJoyStick(Vector3.zero);
  45. }
  46. public Vector3 GetDir()
  47. {
  48. Vector3 dir = new Vector3(content.anchoredPosition3D.x, 0, content.anchoredPosition3D.y);
  49. dir /= mRadius;
  50. return dir;
  51. }
  52. void Update()
  53. {
  54. if (onJoyStick != null)
  55. {
  56. try
  57. {
  58. if (GetDir() != Vector3.zero && canMove)
  59. {
  60. onJoyStick(GetDir());
  61. }
  62. }
  63. catch (Exception e)
  64. {
  65. Debug.LogError(e.ToString());
  66. }
  67. }
  68. }
  69. public void ReHomePos()
  70. {
  71. canMove = false;
  72. content.anchoredPosition3D = Vector3.zero;
  73. onJoyStick(Vector3.zero);
  74. }
  75. }
  76. public delegate void UGUIJoyStickHandle(Vector3 dir);