(유니티) 캐릭터 이동

1. Input.GetKey 함수 사용

캐릭터 게임 오브젝트는 콜라이더와 리지드바디 컴포넌트를 가진다는 전제하에 작성하였습니다.

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

public class Player : MonoBehaviour
{
    public float speed = 10f;
    private Rigidbody playerRigidbody;

    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if(Input.GetKey(KeyCode.W)) // W 입력시
            playerRigidbody.AddForce(0, 0, speed);
        

        if(Input.GetKey(KeyCode.A)) // A 입력시
            playerRigidbody.AddForce(-speed, 0, 0);
        

        if(Input.GetKey(KeyCode.S)) // S 입력시
            playerRigidbody.AddForce(0, 0, -speed);
        

        if(Input.GetKey(KeyCode.D)) // D 입력시
            playerRigidbody.AddForce(speed, 0, 0);
    }
}
  • Input.GetKey는 키입력을 수정할려면 코드를 바꿔야 하는 불편함이 있습니다.
  • 각 방향마다 코드를 작성해야 하므로 코드가 길어집니다(가독성이 떨어진다).

2. Input.GetAxis 함수 사용

유니티 프로젝트에서 Edit -> Project Settings -> Axes에 들어가면 Input.GetAxis 에서 맵핑 되어있는 기능을 확인할 수 있습니다.

위 사진의 빨간색 박스는 왼쪽, 오른쪽 화살표와 보조키로 a, d키를 의미한다. 즉, 키보드 수평방향에 대응되는 키가 맵핑되어있습니다.

GetAxis는 Negative에서 Positive로 이동할 때 점진적으로 증가합니다.

GetKey는 0(안 눌렀을 때), 1(눌렀을 때) 두 가지 경우가 있지만 GetAxis는 -0.5, 0.2, 0.3와 같이 소수점 결과값도 나올 수 있습니다. 즉, 걷기, 천천히 뛰기, 달리기를 구분할 수 있습니다.

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

public class Player : MonoBehaviour
{
    public float speed = 10f;
    private Rigidbody playerRigidbody;

    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody>();
    }

    void Update()
    {
        float inputX = Input.GetAxis("Horizontal");
        float inputZ = Input.GetAxis("Vertical");

        /*
         * AddForce를 사용하면 게임 오브젝트에게
         * 속도를 주는게 아니라 힘을 주는 것이다.
         * 즉, 힘이 추가될 수록
         * 점진적으로 속도가 증가한다.
         */
        //playerRigidbody.AddForce(inputX * speed, 0, inputZ * speed);

        float fallSpeed = playerRigidbody.velocity.y;

        Vector3 velocity = new Vector3(inputX, 0, inputZ);
        velocity *= speed; //(inputX, 0, inputZ)*speed
        velocity.y = fallSpeed;

        /*
         * velocity는 게임 오브젝트의
         * 속도를 바로 덮어씌운다.
         * 주의해야 할 점은,
         * 추락할 때의 속도이다.
         * 처음 추락할 때 속도를
         * 유지시켜 주는 것이 중요하다.
         */
        playerRigidbody.velocity = velocity;

    }
}
  • 조이스틱에도 자동으로 대응됩니다.
  • 게이머가 키 커스터마이징을 가능하도록 코드를 작성할 수 있습니다.

댓글 달기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다