- Home /
Simple Rotation
Hey guys,
I'm new to unity and i'm already stuck on what seems to me as the simplest of functionality. I can't get the hang of rotations..
Let's say i have a Vector3(0,5,0)
and i want to rotate it 30 degrees over the x-axis and 55 degrees over the y-axis, with pivot point Vector3(0,0,0)
.
How would one go about to achieve this? I have been wrestling with Quaternions and Transforms, but to no avail..
Any help is most welcome!
Answer by CHPedersen · Mar 04, 2011 at 11:41 AM
There are several ways. Quaternions, though more complicated if you dig into their math, present the simpler alternative in terms of lines of code.
With quaternions, you can instantiate a Quaternion object using one of the static methods in the Quaternion class. You mention rotations about specific axes, so we can use the AngleAxis method to create a suitable quaternion. These are then multiplied onto the vector you wish to rotate. The result is the rotated vector. So the example you described above would be:
Vector3 toBeRotated = new Vector3(0, 5, 0); Quaternion rotateVectorAboutX = Quaternion.AngleAxis(30, new Vector3(1, 0, 0)); Quaternion rotateVectorAboutY = Quaternion.AngleAxis(55, new Vector3(0, 1, 0));
Vector3 afterRotation = rotateVectorAboutX * rotateVectorAboutY * toBeRotated;
Note that the order must always be Quaternion*Vector, never Vector*Quaternion. I'm not a math wizard, but my guess is that this is related to the dimensionality of their underlying matrix representations. When you multiply matrices, the "connecting" dimensions must match, i.e. [1x4][4x4] is okay, but not [4x1][4x4].
There are plenty other ways to go about this, like EulerAngles, if you're more into that.
Thank you very much! I've been trying to get this to work for a week, searching the forums like crazy. But this is very clear example!
wow, I never knew you could multiply Quaternions by Vectors, I guess this is some of the underlying reasoning behind Quaternions being called Euler parameters?
[edit:] and infinite respect btw to this answer.
Your answer
Follow this Question
Related Questions
Quaternion and rotation of object 1 Answer
Is there no way to get reliable angles from a rigidbody? 2 Answers
Quaternion Rotation On Specific Axis Issue 0 Answers
Extrapolating Quaternion Rotation 2 Answers
Make Quaternion affected by float 1 Answer