问题
I'm programming camera controls with a mouse. I want the user to be able to look up and down or left and right but not be able to "tilt" to the side. Put another way, I want to allow Yaw and Pitch to change but restrict Roll to 0.
How can I prevent a Quaternion from rotating around a certain axis? When I only allow x-axis rotation or y-axis rotation by themselves, everything works fine, but when I allow both at the same time for some reason the y-rotation is affected and the camera tilts to the side.
回答1:
As CNuts explained, concatenating multiple yaw and pitch rotations can result in a roll rotation. However, this does not occur if the yaw and pitch rotations are strictly separated in the multiplication order. E.g.
Yaw1 * Yaw2 * Yaw3 * Pitch1 * Pitch2
There will be problems only when another yaw rotation is added to the end. But you can easily prevent this: If you want to add a yaw rotation, multiply it to the left. If you want to add a pitch rotation, multiply it to the right. I.e. if the current camera rotation is R
, then:
R = additionalYaw * R
or
R = R * additionalPitch
Since all the yaw rotations are about the same axis, these transforms actually commute. So it does not matter in what order they appear (same applies to all other rotations about the same axis). Of course, you can also switch the order (i.e. pitch first, then yaw). Depending on what kind of control you want.
CNuts also described an alternative approach. If you have a transform hierarchy, you can have two nodes for your camera transform. Then, add yaw rotations to one of them and pitch rotations to the other. This will have the same effect as described above, effectively separating rotations about different axes.
来源:https://stackoverflow.com/questions/46738139/prevent-rotation-around-certain-axis-with-quaternion