본문 바로가기

Project/도둑과 경호원

[도둑과 경호원] Unity: Player 회전과 이동

728x90

이번에는 Player가 움직이는 키에 맞게 회전하여 움직이는 방법에 대해 알아보겠다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Player : MonoBehaviour
{
    public float moveSpeed = 7;
    public float smoothMoveTime = 0.1f;
    public float turnSpeed = 8;
 
    float angle;
    float smoothInputMagnitude;
    float smoothMoveVelocity;
    bool disabled;
    Vector3 velocity;
 
    Rigidbody rigid;

 

 

  • moveSpeed - 움직이는 속도값을 가지는 변수
  • smoothMoveTime - smoothDamp 속성값으로 움직임 시간에 대한 값을 가지는 변수
  • turnSpeed - 회전하는 속도값을 가지는 변수
  • angle - 플레이어를 회전시킬 각을 저장하는 변수
  • smoothInputMagnitude - smoothDamp 함수의 리턴값을 받게 될 변수
  • smoothMoveVelocity - smoothDamp 속성값으로 현재 속도에 대한 값을 가지는 변수
  • disabled - 플레이어의 존재 유무에 대해 나타내줄 변수이다.
  • velocity - 플레이어가 움직일 다음 좌표를 저장하는 변수
  • rigid - 플레이어를 움직이고, 회전시킬 Rigidbody 변수

 

1
2
3
4
    void Start()
    {
        rigid = GetComponent<Rigidbody>();
    }

 

rigid변수에 플레이어의 Rigidbody를 넣어준다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 void Update()
    {
        Vector3 inputDirection = Vector3.zero;
 
        if (!disabled)
        {
            inputDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
        }
 
        float inputMagnitude = inputDirection.magnitude;
        smoothInputMagnitude = Mathf.SmoothDamp(smoothInputMagnitude, inputMagnitude, ref smoothMoveVelocity, smoothMoveTime);
 
        float targetAngle = Mathf.Atan2(inputDirection.x, inputDirection.z) * Mathf.Rad2Deg;
        angle = Mathf.LerpAngle(angle, targetAngle, Time.deltaTime * turnSpeed * inputMagnitude);
 
        velocity = transform.forward * moveSpeed * smoothInputMagnitude;
    }

 

Mathf.SmoothDamp를 사용하여 smoothMoveTime이 지남에 따라 smoothInputMagnitude에서 inputMagnitude로 이동한다. 그리고 Mathf.Atan2를 이용하여 targetAngle의 값을 구하고, Mathf.LerpAngle을 이용하여 angle에서 targetAngle로 Time.deltaTime * turnSpeed * inputMagnitude의 시간 동안 회전한다.

 

마지막으로 velocity에 플레이어의 정면 방향에 이동속도를 곱하고 smoothInputMagnitude를 곱하여 이동이 자연스럽게 앞으로 가게 해준다.

 

1
2
3
4
5
 void FixedUpdate()
    {
        rigid.MoveRotation(Quaternion.Euler(Vector3.up * angle));
        rigid.MovePosition(rigid.position + velocity * Time.deltaTime);
    }

 

FixedUpdate는 고정된 프레임으로 주기적으로 호출되는 함수이기 때문에 Rigidbody를 이용하여 힘을 적용하는 경우에는 FixedUPdate에서 힘을 적용해준다. 따라서 Update함수에서 구해주었던 angle값과 velocity값을 이용하여 rigid에 회전값과 이동값을 가해준다.

728x90