I already know about the matrices I have to use in order to perform rotations. If I have to rotate in z-axis and then in x-axis, I would do it in 2 steps. My question is, is it possible to combine both rotations into a single matrix? I will appreciate your feedback.
(This answer is essentially the same as Stefan's but I wanted to add some detail about row and column vectors, and how to determine which you are using.)
Yes, this is possible, but the details depend on whether you represent your vectors as rows or columns.
If you are using column vectors, you will normally transform them by left-multiplying your matrices:
vector = mRotateZ * vector; vector = mRotateX * vector;
Of course, you can also do this in one step:
vector = mRotateX * mRotateZ * vector;
But matrix multiplication is associative, which means it doesn't matter which multiplication is performed first:
A * B * C = (A * B) * C = A * (B * C)
So we can write
Matrix mRotate = mRotateX * mRotateZ; vector = mRotate * vector;
We have now created a single matrix, which is equivalent to first rotating about
Z and second about
X. This generalises trivially for any number of transformations. Notice that transformations are applied from right to left.
If, on the other hand, you are using row vectors, you will normally right-multiply your matrices:
vector = vector * mRotateZ; vector = vector * mRotateX;
Again, writing it in one step, we get
vector = vector * mRotateZ * mRotateX;
which can be rewritten as
Matrix mRotate = mRotateZ * mRotateX; vector = vector * mRotate;
Notice that in this case, the transformations applied from left to right.
Yes, just multiply them in reverse order:
Matrix myrotation = Matrix.CreateRotationX(xrot) * Matrix.CreateRotationZ(zrot);
EDIT. My answer only applies if you are using column vectors. Please see Martin Büttner detailed answer.
What this (essentially) means is that:
- Every orientation can be represented as a quaternion
- Quaternions represent a single rotation
- Multiplication of quaternions produces another quaternion (closure), and is equivalent to composing the rotations.
- Therefore any number of rotations can be represented as a single rotation!
Think about that. Starting from object space, you can rotate your object into any orientation using only a single rotation.
I would like to point out that bringing quaternions in wasn't just random math-ese. In contrast to the other answers, the favored approach in graphics is actually to represent rotations as quaternions, since they take up less space and are faster to combine.
There are easily-Googleable ways to convert between rotation matrices and quaternions, depending on which you prefer. The point is that rotations are the quaternions in a mathematical sense, so combinations thereof are also single rotations.