개발일지

241011(금) [스파르타 타운 과제 : 필수 기능]

게임 프로그래머 2024. 10. 11. 21:33

캐릭터 만들기

 

Hierachy창에서 캐릭터 게임 오브젝트를 만들고 Sprite Render를 추가해서

르탄이 이미지를 추가했다. 


캐릭터 이동

처음엔 구 인풋 시스템을 활용한 코드를 복습할겸 썼다.

public class InputManager : MonoBehaviour
{
    Rigidbody2D rb;
    [SerializeField] private float speed;
    // Update is called once per frame

    private void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }
    void Update()
    {
        float vertical = Input.GetAxisRaw("Vertical");
        float horizontal = Input.GetAxisRaw("Horizontal");

        Vector2 direction = new Vector2(vertical, horizontal);

        direction = direction.normalized;

        rb.velocity = direction * speed;
    }
}

 

근데 문제는 w키는 윗키, s는 아랫키, a는 왼쪽, d는 오른쪽으로 가야하는데

 

ws가 좌우, ad가 위아래로 가는 현상이 발생했다.

 

처음에 시도한건 edit → project settings → Input Manager 세팅이 잘못됐나 확인했는데 이상 없었다.

 

??? 이상함을 느낀 찰나에 위 코드 작성 순서가 잘못 됐음을 확인했다..

 

코드수정

Vector2 direction = new Vector2(horizontal, vertical);

 

x축엔 horizontal y축엔 vertical이 와야 했는데 반대로.. 이런..

수정하고 정상 작동했다. 코드 작성시 좀 더 유의해서 작성해야겠다.

 

이대로 다음 과제를 시도할까 생각했지만

강의에서 구인풋시스템이 가진 한계점과 new input system을 이미 언급했고

둘다 알면 좋을 것 같아서 학습을  위해 강의를 다시 복습했다.

 

input 파일을 만들고 파일안에 우클릭 → create → input actions 만들고 더블클릭해 수정

 

Player에 Player Input Actions에 추가하고 rigidbody 2d gravity scale을 0으로(중력 영향x)

이후 PlayerInputController, TopDownMovement 추가


카메라 따라가기

MainCamera에 FollowCamera.cs 추가

 

카메라를 담아줄 target을 변수로 했고

void LateUpdate(플레이어가 움직인 다음에 움직여야 하므로 Update 다음)에서 코드 작성했다.

public class FollowCamera : MonoBehaviour
{
    public Transform target;

    void LateUpdate()
    {
        transform.position = new Vector3(target.position.x, target.position.y, -10f);
    }
}

 

메인 카메라 포지션(transform.position)에 플레이어 포지션(target.position) 좌표값을 대입해준다.

 

조금 부드럽게 이동하려면 Vector3.Lerp(Vector3 A, Vector3 B, float t)를 추가한다.

A에 카메라, B에 플레이어, t에 Time.delta.time을 추가

public class FollowCamera : MonoBehaviour
{
    public Transform target;
    [Range(1f, 5f)] public float speed;

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = new Vector3(target.position.x, target.position.y, -10f);
        transform.position = Vector3.Lerp(transform.position, target.position, Time.deltaTime * speed);
    }
}

아래 영상이 도움이 되었다.

https://youtu.be/nhmc1z9yh0c?si=edIJ8YAqw7wpHbvf