본문 바로가기
Unity

[CharacterController] 캐릭터 이동

by kldaji 2021. 7. 13.

1. Documentation

https://docs.unity3d.com/kr/2019.3/ScriptReference/CharacterController.Move.html

 

CharacterController-Move - Unity 스크립팅 API

A more complex move function taking absolute movement deltas.

docs.unity3d.com

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

public class ${className} : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;

    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }

    void Update()
    {
        if (characterController.isGrounded)
        {
            moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical"));
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }

        moveDirection.y -= gravity * Time.deltaTime;

        characterController.Move(moveDirection * Time.deltaTime);
    }
}

 

2. Rotation 추가

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

public class ClassTest : MonoBehaviour
{
    CharacterController characterController;

    public float speed = 6.0f;
    public float rotateSpeed = 20.0f;
    public float jumpSpeed = 8.0f;
    public float gravity = 20.0f;

    private Vector3 moveDirection = Vector3.zero;
 
    void Start()
    {
        characterController = GetComponent<CharacterController>();
    }
    
    void Update()
    {
        if (characterController.isGrounded)
        {
            moveDirection = new Vector3(0, 0, Input.GetAxis("Vertical"));
            
            // 해당 코드를 추가해주여야 rotate된 방향으로 움직이는데, 
            // 이유를 모르겠다...
            moveDirection = transform.TransformDirection(moveDirection);
            
            moveDirection *= speed;

            if (Input.GetButton("Jump"))
            {
                moveDirection.y = jumpSpeed;
            }
        }
    
        moveDirection.y -= gravity * Time.deltaTime;
        
        characterController.Move(moveDirection * Time.deltaTime);
        
        // Rotate 추가
        transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed * Time.deltaTime, 0);
    }
}

 

※ CharacterController을 통해 Object가 경사로를 따라 움직일 때, 수평을 잃어 기울어지는 것을 방지할 수 있다.

'Unity' 카테고리의 다른 글

Google VR SDK - Android  (0) 2021.07.14
[Animator] 애니메이션  (0) 2021.07.14
물체 충돌  (0) 2021.07.13
[GetButton] Jump  (0) 2021.07.12
[GetKey] Input Keys  (0) 2021.07.12