주녘공부일지

[Unity3D] Rotation (회전) 본문

GameEngine/UnityEngine - Class

[Unity3D] Rotation (회전)

주녘 2022. 2. 21. 20:23
728x90

Rotation (회전)

월드 공간상에서의 트랜스폼의 회전을 나타냄 ( Quaternion으로 저장 )

 

namespace UnityEngine에 선언되어 있는 구조체로, 안에 선언되어 있는 함수들을 활용할 수 있음

 

Quaternion은 복잡한 수를 기반으로 하기에 직관적으로 이해하기 쉽지 않으므로, 회전에 사용한다고만 알아둠

1) transfrom.Rotate

y축으로 회전하는 로직 ( 3줄 모두 같은 결과 )

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

public class PlayerController : MonoBehaviour
{
    float _yAngle = 0f;
    
    void Update()
    {
       transform.Rotate(new Vector3(0f, Time.deltaTime * 100f, 0));
       // y축 방향으로 회전
       
        _yAngle += Time.deltaTime * 100f;
       transform.rotation = Quaternion.Euler(new Vector3(0f, _yAngle, 0f));
       // y축 방향으로 회전 : 오일러각을 쿼터니언으로 변경시켜 사용 (위와 같은 로직)
    }
}

+ Rotate 함수 대신 eulerAngles을 활용하여 회전을 줄 수도 있지만, 360도를 넘어가면 오작동할 수 있으므로 추가 연산을 해주기엔 적합하지 않아 Rotate()를 사용하는 것이 편리함

2) Quaternion Slerp , Quaternion LookRotation

3D 플레이어 이동 구현 예제 ( 이동하는 방향으로 플레이어를 회전시키며 이동 )

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

public class PlayerController : MonoBehaviour
{
    [SerializeField] float _speed = 10.0f;

    void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.forward), 0.2f);
            transform.position += Vector3.forward * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.back), 0.2f);
            transform.position += Vector3.back * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.A))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.left), 0.2f);
            transform.position += Vector3.left * Time.deltaTime * _speed;
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Vector3.right), 0.2f);
            transform.position += Vector3.right * Time.deltaTime * _speed;
        }
    }
}

 

public static Quaternion Slerp ( Quaternion a, Quaternion b, float t )

- 두 개의 회전 값을 정하면 float 비율만큼의 적당한 회전값을 쿼터니언으로 리턴시킴

- 구면 선형 보간법 ( 곡선으로 보간 ) // Lerp : 선형 보간법 ( 직선으로 보간 )

ex) Slerp ( Quaternion  a, Quaternion b, float t )

      t = 0.0f -> a

      t = 0.5f -> a와 b의 딱 중간

      t = 1.0f -> b

 

public static Quaternion LookRotation ( Vector3 forward, Vector3 upwards = Vector3.up );

- 첫번째 인자에 방향 벡터를 입력하면 자기 위치 기준에서의 해당 방향 벡터쪽으로 회전

- 두번째 인자인 upwards은 Vector3.up이 디폴트 값으로 세팅되어 있음

 

+ Quaternion.identity ( 회전 값 0 )

728x90