I'm trying to understand the maths behind rotating an object in all three dimensions. This is for a programming example to rotate all of the vertices of a basic quad shape.
Right now this is what I have:
(v = vertices)
float x = v[i].x * Mathf.Cos(angle * Mathf.Deg2Rad) - v[i].y * Mathf.Sin(angle * Mathf.Deg2Rad);
float y = v[i].x * Mathf.Sin(angle * Mathf.Deg2Rad) + v[i].y * Mathf.Cos(angle * Mathf.Deg2Rad);
The above code rotates the vertices around the Z axis.
Questions:
The first thing that I don't understand is why is the cos and sin being subtracted and added together in order to find the new X and Y location? I understand what sin and cos do and I understand why you have to multiply the current X and Y by them. What I don't understand is why is sin being subtracted by cos for the new X and why is Sin being added to Cos for the new Y?
Right now the code above rotates the object around the Z axis, but I want to rotate around the X and Y axis as well. I don't really know how to adjust the maths in order to do this, I'm hoping I'll have a better idea when I know the answer to my first question, but if anyone could explain how to rotate it around the other axis then that'd be helpful.
Thanks
In 2 dimensions ($ \mathbb R^2 $), rotating a vector $ (x\ y) $ by a positive angle $ \vartheta $ is obtained by left multiplying it by the matrix $$ R = \begin{pmatrix}\cos\vartheta & -\sin\vartheta \\ \sin\vartheta & \cos\vartheta \end{pmatrix}. $$
You can show this in a number of ways, for instance by requiring that your new vector have the same length as the one you started with (then you find that $ \det R $ needs to be $ \pm 1 $, with the minus sign corresponding to a reflection, while a pure rotation has determinant one).
Intuitively speaking, in a 2-dimensional rotation one of the coordinates is necessarily increasing, while the other is simultaneously decreasing in modulus (hence the minus sign).
In three dimensions, rotating about the $ z $ axis is simply obtained via the matrix $$ R(z) = \begin{pmatrix}\cos\vartheta & -\sin\vartheta & 0 \\ \sin\vartheta & \cos\vartheta & 0 \\ 0 & 0 & 1 \end{pmatrix}, $$ which provides the rotation of the $ xy $ coordinates while leaving $ z $ unchanged. Now, since the way we are labeling the axes is arbitrary, you may switch rows and columns in order to see that rotations about the other axes are given by $$ R(x) = \begin{pmatrix}1 & 0 & 0 \\ 0 & \cos\vartheta & -\sin\vartheta \\ 0 & \sin\vartheta & \cos\vartheta \end{pmatrix}, \qquad R(y) = \begin{pmatrix}\cos\vartheta & 0 & -\sin\vartheta \\ 0 & 1 & 0 \\ \sin\vartheta & 0 & \cos\vartheta \end{pmatrix}. $$