4
votes

Transform.Rotate has a very helpful interface for selecting whether or not a rotation should be made relative to world axes or the local axes.

Behind the scenes, it's doing some math to the transform's rotation, a Quaternion, with another Quaternion. And the exact nature of this math changes depending on if you choose the local or world flag.

How can I do this sort of math without assigning the first Quaternion to a Transform's rotation (wasting memory and/or time) just to do some math with it?

Suppose my first Quaternion is Quaternion q1 = Quaternion.Euler(0f,0f,90f); and the second is Quaternion q2 = Quaternion.Euler(90f,0f,0f).

Applying the second to the first along its local axes would give a rotation that rotates its right side to face down and its front to face right.

Applying the second to the first along the original axes would give a rotation that rotates its back to face down and its top to face right.

1

1 Answers

6
votes

Use the Quaternion operator *.

In Unity, when you multiply two quaternions, it applies the second quaternion (expressed in global axes) to the first quaternion along the local axes produced after the first Quaternion).

So, if you want to do the equivalent of Rotate(q2, Space.Self), where q1 is the transform's original rotation, and q3 is the transform's new rotation, you want Quaternion q3 = q1 * q2.


What do you do if you want to apply q2 to q1 along the axes before q1 applies (i.e., along the global axes)? Well, it turns out that is equivalent to applying q1 along the local axes of q2.

As an example, applying q2 along the global axes of q1 rotates its back to face down and its top to face right. Consider that that applying q1 along the local axes of p2 also rotates its back to face down and its top to face right. They result in the same orientation!

So what does that mean? If you want to apply q2 to q1 along the axes before q1 applies, then do Quaternion q3 = q2 * q1.

This is the equivalent of doing Rotate(q2, Space.World) where q1 is the transform's original rotation, and q3 is the new rotation.


Unlike Rotate, you can use this operator to rotate an object relative to its parent's axes! If you do transform.localRotation = q2 * transform.localRotation, you will be rotating the object relative to the axis of the parent.