Unity/베어유 : 어몽어스 개발 노트

[6강] 캐릭터 만들기 : 조이스틱 이동

서니션 2023. 1. 7. 15:22
728x90
반응형

조이스틱 만들고 이미지도 넣고.. 등등 기본 세팅하고

위치 설정해줌

 

기존 조이스틱 아래에 스틱을 하나 두어

조이스틱의 투명도를 낮춰준다

 

조이스틱 스크립트를 만들어서 캐릭터에 넣어주고

스크립트를 정리해준다

 

 

Joystick.cs

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

// 1. 스틱 드래그 + 제한
// 2. 드래그한만큼 캐릭터 이동
public class JoyStick : MonoBehaviour
{
    public RectTransform stick, backGround;
    PlayerCtrl PlayerCtrl_script;
    
    bool isDrag;
    float limit;

    private void Start()
    {
        PlayerCtrl_script = GetComponent<PlayerCtrl>();
        limit = backGround.rect.width * 0.5f;
    }

    private void Update()
    {
        // 드래그하는 동안
        if (isDrag)
        {
            Vector2 vec = Input.mousePosition - backGround.position;
            stick.localPosition = Vector2.ClampMagnitude(vec, limit);

            Vector3 dir = (stick.position - backGround.position).normalized; // 정규화
            transform.position += dir * PlayerCtrl_script.speed * Time.deltaTime;
            
            // 드래그 끝나면
            if (Input.GetMouseButtonUp(0))
            {
                stick.localPosition = new Vector3(0, 0, 0);
                isDrag = false; // 다시 원위치로
            }
        }
    }

    // 스틱을 누르면 호출
    public void ClickStick()
    {
        isDrag = true;
    }
}

 

PlayerCtrl.cs 수정

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCtrl : MonoBehaviour
{
    public GameObject joyStick;
    public float speed;
    // 인스펙터 창에서 설정하기 위해 public으로 작성
    public bool isJoyStick;
    
    private void Start()
    {
        Camera.main.transform.parent = transform;
        // 메인 카메라의 부모를 지정. 캐릭터가 메인 카메라의 부모가 되는 것. 이 transform은 캐릭터꺼
        Camera.main.transform.localPosition = new Vector3(0, 0, -10);
        // 캐릭터가 어떤 위치에서 생겨도 카메라 0으로 설정해주어야함
        // 2D는 z값이 필요 없지만, 카메라는 기본 z축이 -10임
    }

    private void Update()
    {
        Move();
    }

    // 캐릭터 움직임 관리
    void Move()
    {
        if (isJoyStick)
        {
            joyStick.SetActive(true);
        }
        else
        {
            joyStick.SetActive(false);
            // 클릭했는지 판단
            if (Input.GetMouseButton(0))
            {
                Vector3 dir = (Input.mousePosition - new Vector3(Screen.width * 0.5f, Screen.height * 0.5f)).normalized;
                // 클릭한 값 - 스크린의 가운데 -> 어느 방향으로 터치를 했는지 알 수 있음
                // .normalized로 정규화. 방향 벡터로 바뀌어서 방향을 알 수 있음. dir에 저장
                transform.position += dir * speed * Time.deltaTime;
                // transform에 계속해서 추가. 기기마다 속도가 다를 수 있기 때문에 Time.deltaTime(실제시간)을 곱해줌
            }
        }
        
    }
}

 

조이스틱 만들기 재밌었다!!

728x90
반응형