65 lines
1.5 KiB
C#
65 lines
1.5 KiB
C#
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
|
|
public class JoystickController : MonoBehaviour, IPointerDownHandler, IDragHandler, IPointerUpHandler
|
|
{
|
|
[Header("Joystick UI")]
|
|
public RectTransform background;
|
|
public RectTransform handle;
|
|
|
|
[Header("Output")]
|
|
public Vector2 arahInput;
|
|
|
|
private float radius;
|
|
|
|
private void Start()
|
|
{
|
|
if (background == null)
|
|
{
|
|
background = GetComponent<RectTransform>();
|
|
}
|
|
|
|
radius = background.sizeDelta.x / 2f;
|
|
|
|
if (handle != null)
|
|
{
|
|
handle.anchoredPosition = Vector2.zero;
|
|
}
|
|
}
|
|
|
|
public void OnPointerDown(PointerEventData eventData)
|
|
{
|
|
OnDrag(eventData);
|
|
}
|
|
|
|
public void OnDrag(PointerEventData eventData)
|
|
{
|
|
Vector2 posisiSentuh;
|
|
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(
|
|
background,
|
|
eventData.position,
|
|
eventData.pressEventCamera,
|
|
out posisiSentuh
|
|
);
|
|
|
|
posisiSentuh = Vector2.ClampMagnitude(posisiSentuh, radius);
|
|
|
|
if (handle != null)
|
|
{
|
|
handle.anchoredPosition = posisiSentuh;
|
|
}
|
|
|
|
arahInput = posisiSentuh / radius;
|
|
}
|
|
|
|
public void OnPointerUp(PointerEventData eventData)
|
|
{
|
|
arahInput = Vector2.zero;
|
|
|
|
if (handle != null)
|
|
{
|
|
handle.anchoredPosition = Vector2.zero;
|
|
}
|
|
}
|
|
} |