Search code examples
unity-game-enginegraphicsgeometryquaternions

Rotate a quaternion / Change the axis it rotates around


Conceptually a quaternion can store the rotation around an axis by some degree. Now, what is the numerically most robust and least calculation intensive way to rotate the axis?

For example when i have a quaternion, which rotates 90 degrees around the y-axis and i want those 90 degrees to be applied to some other arbitrary axis, described by a normalized vector.

EDIT: Since this also came up i added an answer on how to correctly change the axis a quaternion rotates around with another quaternion.


Solution

  • It is a bit unclear what your actual goal is by doing what you describe.

    In order to actually keep the angle but change the axis you would use Quaternion.ToAngleAxis, alter the axis and then pass it back into Quaternion.AngleAxis

    like e.g.

    Quaternion someRotation;
    
    someRotation.ToAngleAxis(out var angle, out var axis);
    
    var newAxis = Vector3.up;
    var newRotation = Quaternion.AngleAxis(angle, new axis);
    

    Or you rotate an existing Quaternion by another one using * like

    Quaternion newRotation = someRotation * Quaternion.Euler(90, 0, 0);
    

    which would take the existing rotation and rotate it by 90° around the X axis.