How do I rotate a Quaternion with 2nd Quaternion on its local or world axes without using transform.Rotate?

这一生的挚爱 提交于 2019-12-18 05:16:21

问题


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:


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? 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.



来源:https://stackoverflow.com/questions/56246893/how-do-i-rotate-a-quaternion-with-2nd-quaternion-on-its-local-or-world-axes-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!