Search code examples
c#unity-game-enginequaternionseuler-angles

Understanding quaternions in Unity


Having some difficulty in understanding how to use rotation (represented as a quaternion) in Unity.

What I want to do is note the rotation of an object at some time, then find out its new rotation shortly later, and turn that into how many degrees (or radians) of rotation around the X, Y and Z axes in the world space have occurred.

I am sure it is simple enough ....


Solution

  • You can get the difference between two Quaternion by using Quaternion.Inverse and * operator

    First store the rotation in a field

    private Quaternion lastRotation;
    
    // E.g. at the beginning
    private void Awake()
    {
        lastRotation = transform.rotation;
    }
    

    and then somewhere later do e.g.

    Quaternion currentRotation = transform.rotation;
    Quaternion delta = Quaternion.Inverse(beforeRotation) * currentRotation;
    // and update lastRotation for the next check
    lastRotation = currentRotation;
    

    and then you get the Euler axis angles representation using Quaternion.eulerAngles

    var deltaInEulers = delta.eulerAngles;
    Debug.Log($"Rotated about {deltaInEulers}");