객체가 움직이는 방향으로 회전하도록 구현해보자.
이전 글의 PlayerMovement 스크립트를 수정한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5;
void Update()
{
... 중략
// 월드좌표 기준으로 이동하도록 수정
transform.Translate(movementDirection * speed * Time.deltaTime, Space.World);
if (movementDirection != Vector3.zero)
{
/* 방향값을 바꿔 회전하기 */
transform.forward = movementDirection;
}
}
}
Quaternion을 이용하여 자연스러운 회전을 구현해보자.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5;
public float rotationSpeed = 720;
void Update()
{
... 중략
// 월드좌표 기준으로 이동하도록 수정
transform.Translate(movementDirection * speed * Time.deltaTime, Space.World);
if (movementDirection != Vector3.zero)
{
/* 캐릭터가 특정 속도로 이동 방향을 향해 회전하도록하기 */
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
}
}
}
rotationSpeed의 값이 클수록 회전이 빨라진다.
Quaternion.LookRotation
public static Quaternion LookRotation (Vector3 forward, Vector3 upwards= Vector3.up);
forward: 회전할 방향
upwards: 기준 축
Return: 회전할 방향을 바라보는 Quaternion
Quaternion.RotateTowards
public static Quaternion RotateTowards (Quaternion from, Quaternion to, float maxDegreesDelta);
from: 현재 rotation
to: 목표 rotation
maxDegreesDelta: 회전 속도
return: 회전 속도로 회전한 결과