본문 바로가기
Unity

[Unity] 유니티 간단한 조이스틱 캐릭터 조작

by 코모's 2023. 10. 16.
반응형

유니티에서 제공하는 IDragHandler, IPointerUpHandler, IPointerDownHandler 를 사용하여 만들었다.
각각 드래그 했을때, 클릭후 손을땠을때, 클릭했을 때 의 동작하는 함수이다.
 
고정된 조이스틱이 아닌 일정 판넬 내에서 터치하는곳에 조이스틱이 나타나도록 구현하였다.
 
조이스틱 스크립트

public class JoystickController : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler
{
    [SerializeField]
    private RectTransform joyStick = null;	//조이스틱 뒷배경

    [SerializeField]
    private RectTransform handle = null;	//조이스틱 핸들

    private float handleDeadZone = 1f;		//조이스틱 핸들이 움직일수있는 범위
    public Vector2 direction { get; private set; } = Vector2.zero;	//조이스틱의 방향

    public bool isPress { get; private set; } = false;	//조이스틱의 동작 여부

    private void Awake()
    {
        handleDeadZone = joyStick.rect.width * 0.5f - handle.rect.width * 0.5f;
        // 핸들이 움직일 수 있는 범위를 계산
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        isPress = true;
        SetJoystickPosition(eventData);
        joyStick.gameObject.SetActive(true);
    }

    private void SetJoystickPosition(PointerEventData eventData)
    {
        if (handle == null || joyStick == null)
        {
            return;
        }
        
        //스크린에 조이스틱 출력
        joyStick.position = eventData.position;
        handle.position = joyStick.position;
    }

    public void OnDrag(PointerEventData eventData)
    {
        var handlePosition = eventData.position;
        var value = handlePosition - (Vector2)joyStick.position;	//핸들이 움직인 방향백터

		드래그한 범위가 DeadZone보다 크다면 DeadZone의 크기로 고정
        if (value.magnitude > handleDeadZone)
        {
            handlePosition = (Vector2)joyStick.position + value.normalized * handleDeadZone;
        }

		//핸들의 위치 변경
        if(handle != null)
        {
            handle.position = handlePosition;
        }

		//백터의 nomalized는 방향이다
        direction = value.normalized;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
    	//각종 값 초기화
        isPress = false;
        direction = Vector2.zero;
        handle.anchoredPosition = Vector2.zero;
        joyStick.gameObject.SetActive(false);
    }
}

 
플레이어 스크립트

public class Player : MonoBehaviour
{
    [SerializeField]
    private JoystickController joystick = null;	//조이스틱 연결

    private Rigidbody2D rigid;	//플레이어 Rigidbody

    private float speed = 3f;	//기본 속도

    private void Start()
    {
        rigid = this.GetComponent<Rigidbody2D>();
    }

    private void FixedUpdate()
    {
        MoveJoystick();
    }

    private void MoveJoystick()
    {
    	//조이스틱이 실행 중 일때만 동작하도록 설정
        if(joystick == null || !joystick.isPress)
        {
            return;
        }
		
        // 움질일 방향 X  속도 X 델타 타임
        MovePlayer(joystick.direction * speed * Time.fixedDeltaTime);
    }

    private void MovePlayer(Vector2 nextVec)
    {
        if (rigid != null)
        {
        	//현재 위치 + 나아갈위치
            rigid.MovePosition(rigid.position + nextVec);
        }
    }
}

 

반응형

'Unity' 카테고리의 다른 글

[Unity, C#] Quaternion 종류 및 간단한 사용법  (0) 2023.12.12