Advertisement
Diamond32_Tutoriales

Joystick

May 23rd, 2021
970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5.  
  6. public class Joystick : MonoBehaviour, IDragHandler
  7. {
  8.     Vector2 startPos;
  9.     public Canvas canvas;
  10.     public float Radius;
  11.     public Vector2 Axis;
  12.  
  13.     private void Start()
  14.     {
  15.         startPos = this.transform.position;
  16.     }
  17.  
  18.     public Vector2 axis
  19.     {
  20.         get
  21.         {
  22.             return Axis;
  23.         }
  24.     }
  25.  
  26.     public float Horizontal
  27.     {
  28.         get
  29.         {
  30.             return Axis.x;
  31.         }
  32.     }
  33.  
  34.     public float Vertical
  35.     {
  36.         get
  37.         {
  38.             return Axis.y;
  39.         }
  40.     }
  41.  
  42.     public bool isMoving
  43.     {
  44.         get
  45.         {
  46.             return Axis != Vector2.zero;
  47.         }
  48.     }
  49.  
  50.     public void OnDrag (PointerEventData data)
  51.     {
  52.         Vector2 pos;
  53.  
  54.         RectTransformUtility.ScreenPointToLocalPointInRectangle (canvas.transform as RectTransform, Input.mousePosition, canvas.worldCamera, out pos);
  55.         Vector2 newpos = this.transform.position = canvas.transform.TransformPoint (pos) - (Vector3)startPos;
  56.         newpos.x = Mathf.Clamp(newpos.x, -Radius, Radius);
  57.         newpos.y = Mathf.Clamp(newpos.y, -Radius, Radius);
  58.  
  59.         Axis = pos / Radius;
  60.  
  61.         this.transform.localPosition = newpos;
  62.     }
  63.  
  64.  
  65.     public void OnMouseUp()
  66.     {
  67.         this.transform.localPosition = startPos;
  68.         Axis = Vector2.zero;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement