ltrout

Joystick

Apr 14th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.48 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. using UnityEngine.EventSystems;
  5.  
  6. public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
  7. {
  8.     public RectTransform bgImg;
  9.     public RectTransform joystickImg;
  10.     public Vector3 inputVec;
  11.  
  12.     void Start ()
  13.     {
  14.         bgImg = GetComponent<RectTransform> ();
  15.         joystickImg = transform.GetChild (0).GetComponent<RectTransform> ();
  16.     }
  17.  
  18.     public virtual void OnDrag(PointerEventData ped)
  19.     {
  20.         Vector2 pos;
  21.  
  22.         if(RectTransformUtility.ScreenPointToLocalPointInRectangle( bgImg,
  23.             ped.position,
  24.             ped.pressEventCamera, out pos ))
  25.         {
  26.             pos.x = ( pos.x / bgImg.sizeDelta.x );
  27.             pos.y = ( pos.y / bgImg.sizeDelta.y );
  28.  
  29.             inputVec = new Vector3( pos.x * 2 + 1, 0, pos.y * 2 - 1 );
  30.             inputVec = ( inputVec.magnitude > 1.0f ) ? inputVec.normalized : inputVec;
  31.  
  32.             joystickImg.anchoredPosition =
  33.                 new Vector3( inputVec.x * ( bgImg.sizeDelta.x / 3 ),
  34.                     inputVec.z * ( bgImg.sizeDelta.y / 3 ) );
  35.         }
  36.     }
  37.  
  38.     public virtual void OnPointerDown(PointerEventData ped)
  39.     {
  40.         OnDrag( ped );
  41.     }
  42.  
  43.     public virtual void OnPointerUp(PointerEventData ped)
  44.     {
  45.         inputVec = Vector3.zero;
  46.         joystickImg.anchoredPosition = Vector3.zero;
  47.     }
  48.  
  49.     public float Horizontal ()
  50.     {
  51.         if (inputVec.x != 0)
  52.             return inputVec.x;
  53.         else
  54.             return Input.GetAxis ("Horizontal");
  55.     }
  56.  
  57.     public float Vertical ()
  58.     {
  59.         if (inputVec.z != 0)
  60.             return inputVec.z;
  61.         else
  62.             return Input.GetAxis ("Vertical");
  63.     }
  64. }
Add Comment
Please, Sign In to add comment