Advertisement
Muk99

JoystickUnity5.1

Aug 23rd, 2015
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.09 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4.  
  5. public enum JoystickType {
  6.     Round,
  7.     Square
  8. }
  9.  
  10. public struct Bounds {
  11.     public Vector2 min;
  12.     public Vector2 max;
  13. }
  14.  
  15. public class Joystick : MonoBehaviour, IDragHandler, IEndDragHandler {
  16.  
  17.     public Vector2 output {
  18.         get {
  19.             return p_output;
  20.         }
  21.     }
  22.  
  23.     public JoystickType joystickType = JoystickType.Round;
  24.     public Vector2 deadZone = Vector2.zero;
  25.     public float maxDistance = 50f;
  26.     public bool smooth = true;
  27.  
  28.     new private RectTransform transform;
  29.     private Bounds bounds;
  30.     private Vector2 defaultPosition;
  31.     private Vector2 position;
  32.     private Vector2 p_output;
  33.  
  34.     private void Start() {
  35.         transform = GetComponent<RectTransform>();
  36.         defaultPosition = transform.position;
  37.  
  38.         bounds.max = (Vector2)transform.position + Vector2.one * maxDistance;
  39.         bounds.min = (Vector2)transform.position - Vector2.one * maxDistance;
  40.     }
  41.  
  42.     public void OnDrag(PointerEventData data) {
  43.         position = transform.position;
  44.         position += data.delta;
  45.  
  46.         switch(joystickType) {
  47.             case JoystickType.Round:
  48.             position = Vector2.ClampMagnitude(position - defaultPosition, maxDistance) + defaultPosition;
  49.             break;
  50.             case JoystickType.Square:
  51.             position.x = Mathf.Clamp(position.x, bounds.min.x, bounds.max.x);
  52.             position.y = Mathf.Clamp(position.y, bounds.min.y, bounds.max.y);
  53.             break;
  54.         }
  55.  
  56.         p_output = position - defaultPosition;
  57.         p_output /= maxDistance;
  58.  
  59.         if(Mathf.Abs(p_output.x) < deadZone.x)
  60.             p_output.x = 0f;
  61.         if(Mathf.Abs(p_output.y) < deadZone.y)
  62.             p_output.y = 0f;
  63.  
  64.         if(smooth) {
  65.             p_output.x *= Mathf.Abs(p_output.x);
  66.             p_output.y *= Mathf.Abs(p_output.y);
  67.         }
  68.  
  69.         transform.position = position;
  70.     }
  71.  
  72.     public void OnEndDrag(PointerEventData data) {
  73.         transform.position = defaultPosition;
  74.         p_output = Vector2.zero;
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement