[Unity] Freeze Rotation을 설정해도 LookAt은 해당 축으로 회전하게 할 수 있다

지즈·2025년 2월 11일
0

Unity

목록 보기
10/17

문제

분명 오브젝트의 Rigidbody > Constraints 에서 X 축과 Z 축의 회전을 막아뒀는데, LookAt() 함수를 사용하자 Transform.Rotation이 미세하게 변하는 걸 발견했다.

검색 결과, ConstraintFreeze ~ 들은 물리엔진이 오브젝트의 회전이나 위치 변경을 못하도록 막는 기능이었던 반면, LookAt은 오브젝트의 Transform을 직접 변경하는 것이라 둘 사이의 예기치 않은 동작이 발생했던 것이다.

해결 방법.1

transform.LookAt(new Vector3(_destPos.x, transform.position.y, _destPos.z));

조금 번잡한 감이 있지만 아무튼 간에 transform.position.y 를 직접 지정했다. 내 경우에는 LookAt에 지정한 _destPos.y가 오브젝트의 transform.position.y와 달라서 발생했던 문제였기 때문에 쉽게 해결할 수 있었다.

그외에도 여러 방법들이 있다.

해결방법.2

Vector3 direction = target.position - transform.position;
direction.y = 0; // y축만 회전하도록 제한
transform.rotation = Quaternion.LookRotation(direction);

LookAt()을 사용하지 않고 직접 transform을 회전시키는 것이다.

해결방법.3

Vector3 direction = target.position - transform.position;
direction.y = 0; 
Quaternion targetRotation = Quaternion.LookRotation(direction);
rb.MoveRotation(targetRotation);

만약 오브젝트가 Rigidbody 를 가졌다면, Constratins의 회전 제약이 적용되므로, LookRotation()MoveRotation()을 이용하여 다른 지점을 바라보게 할 수 있다.

profile
클라이언트 개발자가 되는 그 날까지 킵 고잉

0개의 댓글