Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- public class Joystick : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
- {
- public RectTransform bgImg;
- public RectTransform joystickImg;
- public Vector3 inputVec;
- void Start ()
- {
- bgImg = GetComponent<RectTransform> ();
- joystickImg = transform.GetChild (0).GetComponent<RectTransform> ();
- }
- public virtual void OnDrag(PointerEventData ped)
- {
- Vector2 pos;
- if(RectTransformUtility.ScreenPointToLocalPointInRectangle( bgImg,
- ped.position,
- ped.pressEventCamera, out pos ))
- {
- pos.x = ( pos.x / bgImg.sizeDelta.x );
- pos.y = ( pos.y / bgImg.sizeDelta.y );
- inputVec = new Vector3( pos.x * 2 + 1, 0, pos.y * 2 - 1 );
- inputVec = ( inputVec.magnitude > 1.0f ) ? inputVec.normalized : inputVec;
- joystickImg.anchoredPosition =
- new Vector3( inputVec.x * ( bgImg.sizeDelta.x / 3 ),
- inputVec.z * ( bgImg.sizeDelta.y / 3 ) );
- }
- }
- public virtual void OnPointerDown(PointerEventData ped)
- {
- OnDrag( ped );
- }
- public virtual void OnPointerUp(PointerEventData ped)
- {
- inputVec = Vector3.zero;
- joystickImg.anchoredPosition = Vector3.zero;
- }
- public float Horizontal ()
- {
- if (inputVec.x != 0)
- return inputVec.x;
- else
- return Input.GetAxis ("Horizontal");
- }
- public float Vertical ()
- {
- if (inputVec.z != 0)
- return inputVec.z;
- else
- return Input.GetAxis ("Vertical");
- }
- }
Add Comment
Please, Sign In to add comment