GameDev/[Unity]

[유니티]유니티에서 타겟의 Vector3를 기준으로 오브젝트가 바라보게 하는 방법

Bit by Bit 2024. 12. 18. 10:59
728x90

 Unity에서 오브젝트를 특정 타겟의 위치를 기준으로 바라보게 하는 경우는 게임 개발에서 매우 흔한 작업 중 하나입니다. 이 글에서는 Vector3 좌표만을 활용하여 오브젝트가 타겟을 바라보게 하는 방법을 다루며, 추가로 Y축 회전만 허용하는 경우도 함께 설명합니다.


기본 개념: LookAt 함수

Unity는 Transform 클래스에서 제공하는 LookAt 메서드를 사용해 간단히 타겟을 바라보게 만들 수 있습니다. 그러나 LookAt은 Transform을 필요로 하기 때문에, 타겟의 Vector3 좌표만 주어졌을 때는 별도의 처리가 필요합니다.


1. 모든 축을 고려한 회전 구현

타겟의 Vector3를 기준으로 오브젝트가 완전히 바라보게 하려면, Quaternion.LookRotation을 사용합니다. 이는 Vector3 방향을 기준으로 적절한 회전을 계산해 줍니다.

public class LookAtTarget : MonoBehaviour
{
    public Vector3 targetPosition; // 타겟의 위치

    void Update()
    {
        // 현재 오브젝트가 타겟을 바라보게 만듭니다.
        Vector3 direction = targetPosition - transform.position; // 방향 계산
        transform.rotation = Quaternion.LookRotation(direction);
    }
}

코드 설명

  1. targetPosition: 바라보고자 하는 타겟의 좌표입니다.
  2. direction: 현재 오브젝트와 타겟 간의 방향 벡터를 계산합니다.
  3. Quaternion.LookRotation: 방향 벡터를 회전에 매핑하여 오브젝트를 회전시킵니다.

2. Y축 회전만 허용하는 경우

3D 게임에서는 오브젝트가 수평면에서만 회전하도록 제한하는 경우가 많습니다. 이를 위해 Y축 회전을 제외한 나머지 축을 고정합니다.

구현 방법

public class LookAtTargetYAxisOnly : MonoBehaviour
{
    public Vector3 targetPosition; // 타겟의 위치

    void Update()
    {
        // 타겟과의 방향 계산 (Y축 고정)
        Vector3 direction = targetPosition - transform.position;
        direction.y = 0; // Y축 방향 제거

        // 방향이 0이 아닐 경우에만 회전 적용
        if (direction != Vector3.zero)
        {
            transform.rotation = Quaternion.LookRotation(direction);
        }
    }
}

코드 설명

  1. direction.y = 0: Y축 방향을 제거하여 수평면에서만 방향을 계산합니다.
  2. direction != Vector3.zero: 방향 벡터가 0일 경우, Quaternion.LookRotation이 오류를 발생시킬 수 있으므로 체크합니다.

3. Lerp를 활용한 부드러운 회전

타겟을 즉시 바라보는 대신, 부드럽게 회전시키고 싶다면 Quaternion.Lerp를 사용합니다.

모든 축 고려한 부드러운 회전

public class SmoothLookAtTarget : MonoBehaviour
{
    public Vector3 targetPosition; // 타겟의 위치
    public float rotationSpeed = 5f; // 회전 속도

    void Update()
    {
        Vector3 direction = targetPosition - transform.position; // 방향 계산
        Quaternion targetRotation = Quaternion.LookRotation(direction);
        transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
    }
}

Y축 회전만 부드럽게 제한

public class SmoothLookAtTargetYAxisOnly : MonoBehaviour
{
    public Vector3 targetPosition; // 타겟의 위치
    public float rotationSpeed = 5f; // 회전 속도

    void Update()
    {
        Vector3 direction = targetPosition - transform.position;
        direction.y = 0; // Y축 방향 제거

        if (direction != Vector3.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(direction);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * rotationSpeed);
        }
    }
}

코드 설명

  • Quaternion.Lerp: 현재 회전에서 목표 회전까지 점진적으로 이동하도록 보간합니다.
  • rotationSpeed: 회전 속도를 조절할 수 있는 변수입니다.
  • Y축 고정: direction.y = 0을 통해 Y축 이동 제거.

4. 간단한 최적화 팁

1. 고정된 타겟 위치 사용

  • 타겟이 고정된 경우, Update에서 반복적으로 계산하지 않고 한 번만 방향을 설정합니다.
void Start()
{
    Vector3 direction = targetPosition - transform.position;
    transform.rotation = Quaternion.LookRotation(direction);
}

2. 객체 풀링과 병행 사용

  • 프로젝트 타일이나 투사체처럼 반복적으로 생성되는 경우에는 객체 풀링을 활용하여 성능을 최적화합니다.

3. Vector3.Distance로 가까운 타겟만 처리

  • 모든 타겟을 매번 처리하지 않고, 특정 거리 내에 있는 타겟만 회전 계산을 수행합니다.
if (Vector3.Distance(transform.position, targetPosition) < 10f)
{
    // 회전 로직
}

 


 

 유니티에서 타겟의 Vector3 위치만으로 오브젝트가 타겟을 바라보게 하는 방법에는 여러 가지가 있습니다. 간단한 경우 Quaternion.LookRotation을 사용하고, Y축만 회전시키려면 direction.y = 0으로 제한을 추가하면 됩니다. 부드러운 회전이 필요한 경우 Quaternion.Lerp를 활용하여 자연스러운 움직임을 구현할 수 있습니다.

728x90