Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.EventSystems;
- using UnityEngine.UI;
- public class Joystick : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
- {
- private const string HORIZONTAL = "Horizontal";
- private const string VERTICAL = "Vertical";
- [SerializeField] private RectTransform _joystick;
- public Vector2 InputVector { get; private set; }
- private RectTransform _background;
- private void Start()
- {
- _background = GetComponent<RectTransform>();
- _joystick = transform.GetChild(0).GetComponent<Image>().rectTransform;
- }
- public float Horizontal =>
- InputVector.x != 0
- ? InputVector.x
- : Input.GetAxis(HORIZONTAL);
- public float Vertical =>
- InputVector.y != 0
- ? InputVector.y
- : Input.GetAxis(VERTICAL);
- public virtual void OnPointerDown(PointerEventData eventData) => OnDrag(eventData);
- public virtual void OnPointerUp(PointerEventData eventData)
- {
- InputVector = Vector2.zero;
- _joystick.anchoredPosition = Vector2.zero;
- }
- public virtual void OnDrag(PointerEventData eventData)
- {
- Vector2 screenPoint = eventData.position;
- Camera eventCamera = eventData.pressEventCamera;
- bool inRectangle = InRectangle(_background, screenPoint, eventCamera, out Vector2 localPoint);
- if (inRectangle == false)
- return;
- localPoint.x /= SizeDelta.x;
- localPoint.y /= SizeDelta.x;
- InputVector = new Vector2(localPoint.x, localPoint.y).normalized;
- float x = InputVector.x * (SizeDelta.x / 2);
- float y = InputVector.y * (SizeDelta.y / 2);
- var position = new Vector2(x, y);
- _joystick.anchoredPosition = position;
- }
- private Vector2 SizeDelta => _background.sizeDelta;
- private static bool InRectangle
- (RectTransform rect, Vector2 screenPoint, Camera eventCamera, out Vector2 localPoint) =>
- RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, screenPoint, eventCamera, out localPoint);
- }
Advertisement
Advertisement