using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class Joystick : MonoBehaviour { public bool DissappearOnEnd = true; private Vector3 defaultPosition; public bool touchDown; public bool autoConfigMaxDist; public float maxDist = 100; public Vector2 input; private Vector2 deltaPos; private Vector2 startPos; private Vector2 endPos; public RectTransform joyBG; public RectTransform joyStick; void Start(){ defaultPosition = joyBG.localPosition; } public void SetDefaultPosition(Vector2 newDef){ defaultPosition = newDef; endJoy(); } public void onDrag(BaseEventData pointer) { PointerEventData ped = pointer as PointerEventData; endPos = ped.position; deltaPos = endPos - startPos; deltaPos = new Vector2(Mathf.Clamp(deltaPos.x, -maxDist, maxDist), Mathf.Clamp(deltaPos.y, -maxDist, +maxDist)); Vector2 _input = new Vector2(deltaPos.x / maxDist, deltaPos.y / maxDist); if (_input.magnitude < 0.1f) { return; } input = _input; input = (input.magnitude > 1.0f) ? input.normalized : input; joyStick.localPosition = new Vector2(input.x * (joyBG.sizeDelta.x / 2f), input.y * (joyBG.sizeDelta.y / 2f)); } public void pointerDown(BaseEventData pointer) { PointerEventData ped = pointer as PointerEventData; startJoy(ped); } public void pointerUp() { endJoy(); } void startJoy(PointerEventData pointer) { startPos = pointer.position; joyBG.gameObject.SetActive(true); joyStick.gameObject.SetActive(true); joyStick.localPosition = Vector2.zero; joyBG.position = startPos; touchDown = true; } void endJoy() { input=Vector2.zero; joyBG.localPosition = defaultPosition; joyStick.localPosition = Vector2.zero; joyBG.gameObject.SetActive(!DissappearOnEnd); joyStick.gameObject.SetActive(!DissappearOnEnd); touchDown = false; } }