using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class JoyStickHandler : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler { /// /// 摇杆水平偏移量 /// public static float js_x; /// /// 摇杆垂直偏移量 /// public static float js_y; // 当前模式 public static Mode CurrentMode; /// /// 摇杆模式 /// public enum Mode { None, Up, Down, Left, Right }; /// /// 背景图片RectTransform /// [Tooltip("背景图片RectTransform")] public RectTransform background; /// /// Handle的RectTransform /// [Tooltip("Handle的RectTransform")] public RectTransform handle; /// /// 摇杆速度偏移量 /// [Tooltip("摇杆速度偏移量")] public float js_Speed = 1f; /// /// 画布 /// [Tooltip("摇杆所在的画布对象")] private Canvas canvas; // 半径 float radius; // 上下左右的向量 Vector2 up, down, left, right; public bool TestOnEditor; Color handleColor; void Start() { if (!TestOnEditor && !H5Controller.IsMobileBroswer()) { Destroy(gameObject); } canvas = transform.parent.parent.GetComponent(); CurrentMode = Mode.None; radius = background.rect.width / 2.0f; up = new Vector2(0, radius); down = new Vector2(0, -radius); left = new Vector2(-radius, 0); right = new Vector2(radius, 0); handleColor = handle.GetComponent().color; } #region //void Update() //{ // // MessageSend(); //} void MessageSend() { switch (CurrentMode) { case Mode.None: break; case Mode.Up: break; case Mode.Left: break; case Mode.Down: break; case Mode.Right: break; } } #endregion // 鼠标按下 public void OnPointerDown(PointerEventData eventData) { if (BaseController.CanControl) { OnDrag(eventData); handle.GetComponent().color = new Color(150, 150, 150, 255); } } // 鼠标放开 public void OnPointerUp(PointerEventData eventData) { if (BaseController.CanControl) { js_x = 0; js_y = 0; handle.anchoredPosition = Vector2.zero; handle.GetComponent().color = handleColor; CurrentMode = Mode.None; } } // 临时变量 Vector2 to; public void OnDrag(PointerEventData eventData) { if (BaseController.CanControl) { to = (eventData.position - (Vector2)background.position) / canvas.scaleFactor; if (to.magnitude <= radius) { handle.anchoredPosition = to; } else { to = to / (to.magnitude / radius); handle.anchoredPosition = to; } CalcDis(); } } void CalcDis() { float dis = 0f; if (Vector2.Distance(up, handle.anchoredPosition) < dis || dis == 0) { dis = Vector2.Distance(up, handle.anchoredPosition); CurrentMode = Mode.Up; } if (Vector2.Distance(down, handle.anchoredPosition) < dis) { dis = Vector2.Distance(down, handle.anchoredPosition); CurrentMode = Mode.Down; } if (Vector2.Distance(left, handle.anchoredPosition) < dis) { dis = Vector2.Distance(left, handle.anchoredPosition); CurrentMode = Mode.Left; } if (Vector2.Distance(right, handle.anchoredPosition) < dis) { dis = Vector2.Distance(right, handle.anchoredPosition); CurrentMode = Mode.Right; } js_x = (radius - Vector2.Distance(right, handle.anchoredPosition)) / radius * js_Speed; js_y = (radius - Vector2.Distance(up, handle.anchoredPosition)) / radius * js_Speed; } }