[Unity] Joystick

박호준·2022년 2월 15일
0

Unity

목록 보기
17/17
using UnityEngine.EventSystems;
public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    [SerializeField] private RectTransform rect_Background;
    [SerializeField] private RectTransform rect_Joystick;
    [SerializeField] private GameObject go_Player;
    [SerializeField] private float moveSpeed;
    private float   radius;
    private bool    isTouch = false;
    private Vector3 movePosition;


    void Start()
    {
        radius = rect_Background.rect.width * 0.5f;
    }

    void Update()
    {
        if (isTouch)
            go_Player.transform.position += movePosition;
    }

    public void OnDrag(PointerEventData eventData)
    {
        Vector2 value = eventData.position - (Vector2)rect_Background.position;
        value = Vector2.ClampMagnitude(value, radius); // 가두기
        rect_Joystick.localPosition = value;

        float distance = Vector2.Distance(rect_Background.position, rect_Joystick.position) / radius;
        value = value.normalized;
        movePosition = new Vector3(value.x * moveSpeed * distance * Time.deltaTime, 0f, value.y * moveSpeed * distance * Time.deltaTime);
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isTouch = true;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        rect_Joystick.localPosition = Vector3.zero; // 조이스틱 원위치
        movePosition = Vector3.zero;
        isTouch = false;
    }


}
profile
hopark

0개의 댓글