using UnityEngine;
using UnityEngine.EventSystems;
public class JoystickController : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
public RectTransform joystickBackground;
public RectTransform joystickHandle;
private Vector3 inputVector;
private float joystickAmplitude;
private float joystickAngle;
public void OnPointerDown(PointerEventData eventData)
{
OnDrag(eventData);
}
public void OnPointerUp(PointerEventData eventData)
{
inputVector = Vector3.zero;
joystickHandle.anchoredPosition = Vector3.zero;
UpdateJoystickData();
Debug.Log("Joystick Released - Amplitude: " + joystickAmplitude + ", Angle: " + joystickAngle);
}
public void OnDrag(PointerEventData eventData)
{
Vector2 pos;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBackground, eventData.position, eventData.pressEventCamera, out pos))
{
pos.x = (pos.x / joystickBackground.sizeDelta.x);
pos.y = (pos.y / joystickBackground.sizeDelta.y);
inputVector = new Vector3(pos.x * 2 + 1, 0, pos.y * 2 - 1);
inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector;
joystickHandle.anchoredPosition = new Vector3(inputVector.x * (joystickBackground.sizeDelta.x / 3), inputVector.z * (joystickBackground.sizeDelta.y / 3));
UpdateJoystickData();
Debug.Log("Joystick Dragging - Amplitude: " + joystickAmplitude + ", Angle: " + joystickAngle);
}
}
private void UpdateJoystickData()
{
joystickAmplitude = inputVector.magnitude;
joystickAngle = Mathf.Atan2(inputVector.x, inputVector.z) * Mathf.Rad2Deg;
}
public Vector3 GetInputVector()
{
return inputVector;
}
public float GetJoystickAmplitude()
{
return joystickAmplitude;
}
public float GetJoystickAngle()
{
return joystickAngle;
}
}