Advertisement
Pro_Unit

Joystick

Oct 2nd, 2022
1,109
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.89 KB | Gaming | 0 0
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4.  
  5. public class Joystick : MonoBehaviour, IDragHandler, IPointerDownHandler, IPointerUpHandler
  6. {
  7.     private const string HORIZONTAL = "Horizontal";
  8.     private const string VERTICAL = "Vertical";
  9.  
  10.     [SerializeField] private RectTransform _joystick;
  11.     public Vector2 InputVector { get; private set; }
  12.  
  13.     private RectTransform _background;
  14.  
  15.     private void Start()
  16.     {
  17.         _background = GetComponent<RectTransform>();
  18.         _joystick = transform.GetChild(0).GetComponent<Image>().rectTransform;
  19.     }
  20.  
  21.     public float Horizontal =>
  22.         InputVector.x != 0
  23.             ? InputVector.x
  24.             : Input.GetAxis(HORIZONTAL);
  25.  
  26.     public float Vertical =>
  27.         InputVector.y != 0
  28.             ? InputVector.y
  29.             : Input.GetAxis(VERTICAL);
  30.  
  31.     public virtual void OnPointerDown(PointerEventData eventData) => OnDrag(eventData);
  32.  
  33.     public virtual void OnPointerUp(PointerEventData eventData)
  34.     {
  35.         InputVector = Vector2.zero;
  36.         _joystick.anchoredPosition = Vector2.zero;
  37.     }
  38.  
  39.     public virtual void OnDrag(PointerEventData eventData)
  40.     {
  41.         Vector2 screenPoint = eventData.position;
  42.         Camera eventCamera = eventData.pressEventCamera;
  43.  
  44.         bool inRectangle = InRectangle(_background, screenPoint, eventCamera, out Vector2 localPoint);
  45.  
  46.         if (inRectangle == false)
  47.             return;
  48.  
  49.         localPoint.x /= SizeDelta.x;
  50.         localPoint.y /= SizeDelta.x;
  51.  
  52.         InputVector = new Vector2(localPoint.x, localPoint.y).normalized;
  53.  
  54.         float x = InputVector.x * (SizeDelta.x / 2);
  55.         float y = InputVector.y * (SizeDelta.y / 2);
  56.  
  57.         var position = new Vector2(x, y);
  58.  
  59.         _joystick.anchoredPosition = position;
  60.     }
  61.  
  62.     private Vector2 SizeDelta => _background.sizeDelta;
  63.  
  64.     private static bool InRectangle
  65.         (RectTransform rect, Vector2 screenPoint, Camera eventCamera, out Vector2 localPoint) =>
  66.         RectTransformUtility.ScreenPointToLocalPointInRectangle(rect, screenPoint, eventCamera, out localPoint);
  67. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement