ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Math & Physics > 짐벌락 없는 쿼터니언 부드러운 회전 보간(SmoothDamp Rotation)Gimbal-Lock-Free Quaternion SmoothDamp Rotation Interpolation
Math & Physics Advanced Unity 2021.3+ / Unity 6

짐벌락 없는 쿼터니언 부드러운 회전 보간(SmoothDamp Rotation)Gimbal-Lock-Free Quaternion SmoothDamp Rotation Interpolation

Vector3 오일러 각의 360도 경계 래핑 및 짐벌락 문제를 방지하고, 임계 감쇠 스프링-댐퍼 모델로 목표 회전에 부드럽게 수렴하는 쿼터니언 보간 기법입니다.A critically damped spring-damper quaternion interpolation method in C# that avoids Euler 360-degree wrapping and gimbal lock while smoothly converging on target rotations.

#Math #Quaternion #Rotation #Interpolation #Transform
핵심 개념카메라나 캐릭터를 회전시킬 때 Mathf.SmoothDamp를 오일러 각(transform.eulerAngles)에 직접 적용하면 0도와 360도 경계에서 반대 방향으로 한 바퀴 도는 현상이나 짐벌락(Gimbal Lock)이 발생합니다. 쿼터니언의 이중 피복(Double Cover, $q$와 $-q$는 동일한 3D 회전) 특성을 고려해 내적 부호 검사($\text{Dot} < 0$)로 최단 경로 반구를 맞춘 뒤, 각 성분을 감쇠 보간하고 정규화하면 안정적인 회전 감쇠를 구현할 수 있습니다.
Key ConceptApplying Mathf.SmoothDamp directly to Euler angles (transform.eulerAngles) causes sudden 360-degree spin-arounds at the 0°/360° boundary and suffers from gimbal lock. Because quaternions exhibit double cover ($q$ and $-q$ represent the same 3D orientation), checking the dot-product sign ($\text{Dot} < 0$) to align hemispheres before damping and normalizing all four components ensures smooth shortest-path rotation.

1. 쿼터니언 SmoothDamp C# 구현1. Quaternion SmoothDamp Implementation in C#

QuaternionSmoothDamp.cs
using UnityEngine;

public static class QuaternionUtil
{
    public static Quaternion SmoothDamp(
        Quaternion rot, Quaternion target, ref Quaternion deriv, float smoothTime)
    {
        if (Time.deltaTime <= 0.00001f) return rot;

        // 1. 최단 경로 반구 일치 (-q와 q는 동일한 회전이므로 내적이 음수면 부호 반전)
        float dot = Quaternion.Dot(rot, target);
        float multi = dot > 0f ? 1f : -1f;
        target.x *= multi;
        target.y *= multi;
        target.z *= multi;
        target.w *= multi;

        // 2. 4개 성분 독립 SmoothDamp 후 단위 쿼터니언으로 정규화
        Vector4 result = new Vector4(
            Mathf.SmoothDamp(rot.x, target.x, ref deriv.x, smoothTime),
            Mathf.SmoothDamp(rot.y, target.y, ref deriv.y, smoothTime),
            Mathf.SmoothDamp(rot.z, target.z, ref deriv.z, smoothTime),
            Mathf.SmoothDamp(rot.w, target.w, ref deriv.w, smoothTime)
        ).normalized;

        // 3. 현재 회전 벡터와 직교하는 성분만 남기도록 속도 미분값(deriv) 투영 보정
        Vector4 derivError = Vector4.Project(new Vector4(deriv.x, deriv.y, deriv.z, deriv.w), result);
        deriv.x -= derivError.x;
        deriv.y -= derivError.y;
        deriv.z -= derivError.z;
        deriv.w -= derivError.w;

        return new Quaternion(result.x, result.y, result.z, result.w);
    }
}
QuaternionSmoothDamp.cs
using UnityEngine;

public static class QuaternionUtil
{
    public static Quaternion SmoothDamp(
        Quaternion rot, Quaternion target, ref Quaternion deriv, float smoothTime)
    {
        if (Time.deltaTime <= 0.00001f) return rot;

        // 1. Align to shortest-path hemisphere (-q and q represent the same rotation)
        float dot = Quaternion.Dot(rot, target);
        float multi = dot > 0f ? 1f : -1f;
        target.x *= multi;
        target.y *= multi;
        target.z *= multi;
        target.w *= multi;

        // 2. SmoothDamp all 4 components independently and normalize to unit quaternion
        Vector4 result = new Vector4(
            Mathf.SmoothDamp(rot.x, target.x, ref deriv.x, smoothTime),
            Mathf.SmoothDamp(rot.y, target.y, ref deriv.y, smoothTime),
            Mathf.SmoothDamp(rot.z, target.z, ref deriv.z, smoothTime),
            Mathf.SmoothDamp(rot.w, target.w, ref deriv.w, smoothTime)
        ).normalized;

        // 3. Project out radial derivative error to keep velocity tangent to the unit hypersphere
        Vector4 derivError = Vector4.Project(new Vector4(deriv.x, deriv.y, deriv.z, deriv.w), result);
        deriv.x -= derivError.x;
        deriv.y -= derivError.y;
        deriv.z -= derivError.z;
        deriv.w -= derivError.w;

        return new Quaternion(result.x, result.y, result.z, result.w);
    }
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 내적(Quaternion.Dot) 부호 반전의 중요성: 4차원 초구(Hypersphere) 상에서 $q$와 $-q$는 동일한 3D 방향을 가리키지만, 내적이 음수($\text{Dot}(rot, target) < 0$)인 상태에서 그대로 보간하면 최단 경로 대신 360도를 돌아가는 긴 경로(Long Way Around)로 회전하게 됩니다.
  • 4개 성분 모두 독립적인 ref deriv 변수 유지: x, y, z, w 네 성분의 변화율은 서로 다르므로, 속도 참조 변수 deriv 역시 Vector3가 아닌 4개 성분을 모두 가진 Quaternion(또는 Vector4)으로 선언하여 w 성분의 미분값이 x 성분과 섞이지 않게 해야 합니다.
  • 단순 구면 보간 대비 장점: Quaternion.Slerp(rot, target, k * dt)는 시작 시점에 가속도 없이 급격히 꺾이는 느낌을 주지만, SmoothDamp는 2차 임계 감쇠 스프링 모델을 따르므로 출발과 정지 모두에서 관성이 느껴지는 부드러운 카메라 회전을 만들어 줍니다.
  • Hemisphere Alignment via Quaternion.Dot: On the 4D unit hypersphere, $q$ and $-q$ map to the exact same 3D orientation. Interpolating when $\text{Dot}(rot, target) < 0$ takes the long path (up to 360°); negating target when the dot product is negative enforces the shortest arc.
  • Maintain Four Independent Derivative Components: Track angular velocity state in a 4-component Quaternion (or Vector4) ref deriv so that deriv.x, deriv.y, deriv.z, and deriv.w are each damped independently without cross-contaminating channels.
  • Advantage Over Exponential Slerp: While Quaternion.Slerp(rot, target, k * dt) starts with an abrupt velocity jump when the target changes, SmoothDamp models a second-order critically damped spring, providing continuous acceleration at both the start and end of camera turns.

최단 경로 반구 정렬과 탄젠트 공간 미분 투영이 적용된 QuaternionUtil.SmoothDamp를 사용하면, 전방위 3D 우주선 조종이나 TPS 카메라 회전에서 축 꼬임 없이 일관된 감쇠 회전을 얻을 수 있습니다.

Using hemisphere-aligned QuaternionUtil.SmoothDamp with tangent-space derivative projection provides smooth, gimbal-lock-free rotation damping for 6-DoF spacecraft and third-person cameras.

참고자료 & 관련 링크