简易JoyStick实现
支持按键输入WASD,带有方向指示
脚本挂在Handle上,其它的设置
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class JoyStick : MonoBehaviour,IPointerDownHandler,IEndDragHandler,IDragHandler { private RectTransform rectTransform; public RectTransform joyStickBG; public Camera uiCamera; public RectTransform dirArr; public float handleMoveRadius; private float dirArrOffset; public static Action<Vector2> onVelocityChange; public static Action onBeginDrag; public static Action onEndDrag; public Vector2 moveDirection; public bool useKeyBoard = false; private void Awake() { rectTransform = GetComponent<RectTransform>(); dirArr.gameObject.SetActive(false); dirArrOffset = rectTransform.sizeDelta.x * 0.5f; } void Update() { if (onVelocityChange != null) { onVelocityChange(moveDirection); } if (!useKeyBoard) { return; } float x= Input.GetAxis("Horizontal"); float y = Input.GetAxis("Vertical"); Vector2 input = new Vector2(x, y); input = Vector2.ClampMagnitude(input, 1); rectTransform.anchoredPosition = input*handleMoveRadius; if (input.magnitude>=0.95f) { if (!dirArr.gameObject.activeSelf) { dirArr.gameObject.SetActive(true); } dirArr.localRotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(input.y, input.x) * Mathf.Rad2Deg)); dirArr.anchoredPosition = input.normalized * dirArrOffset; } else { if (dirArr.gameObject.activeSelf) { dirArr.gameObject.SetActive(false); } } if (onVelocityChange != null) { onVelocityChange(input); } } public void OnDrag(PointerEventData eventData) { Vector2 moveDir; RectTransformUtility.ScreenPointToLocalPointInRectangle(joyStickBG, Input.mousePosition, uiCamera, out moveDir); if (moveDir.magnitude> handleMoveRadius) { moveDir = moveDir.normalized * handleMoveRadius; if (!dirArr.gameObject.activeSelf) { dirArr.gameObject.SetActive(true); } dirArr.localRotation = Quaternion.Euler(new Vector3(0, 0, Mathf.Atan2(moveDir.y, moveDir.x) * Mathf.Rad2Deg)); dirArr.anchoredPosition = moveDir.normalized * dirArrOffset; } else { if (dirArr.gameObject.activeSelf) { dirArr.gameObject.SetActive(false); } } rectTransform.anchoredPosition = moveDir; moveDirection = moveDir.normalized; } public void OnEndDrag(PointerEventData eventData) { rectTransform.anchoredPosition = Vector2.zero; dirArr.anchoredPosition = Vector2.zero; moveDirection = Vector2.zero; dirArr.gameObject.SetActive(false); if (onEndDrag!=null) { onEndDrag(); } } public void OnPointerDown(PointerEventData eventData) { if (onBeginDrag != null) { onBeginDrag(); } } }