Now when we can project a 3D object on the screen we might also want to be able to move it around, and to rotate it.
The movements are done by simply adding and/or subtracting the right values to the X3,Y3 and Z3.
I'm sorry to say that it isn't quite that easy to rotate a 3D object.
First you'll need to know that all rotations are made about the point (0,0,0) in 3D space. Therefore you'll need to transform(move) the object into a correct position before rotating it and then transform it back to it's original position.
Second of all you'll need to know that the resulting angle of the object is different depending on which of the rotations that are made first, to solve this we'll define an order which the rotations always will follow.
These are the main pitfalls, if you can avoid them you've solved most of the troubles with 3D rotations.
How do we implement the rotations then. To put it all in one word, T R I G O N O M E T R Y. Ok, it looks hard, but it isn't. To quote :
Real programmers aren't afraid of maths
Lithium/VLA
All rotations are based around matrixes but I'll show it in a more simple-to-understand (at least to me) way.
Ok, to rotate about the Z-axis we'll define three new variables : XR, YR and ZR. These represents the resulting coordinates.
You might know that you can draw a circle by putting X=cos(angle)*radius and Y=sin(angle)*radius. We'll use this to rotate our 3D coordinates.
The XR should equal to X3 when the angle is set to zero. If the angle is set to 90 degrees the XR should equal to Y3. This also applies to the YR but reversed.
Sinus for 0 degrees is 0 and cosinus for the same angle is 1. This gives us the formulas :
XR = cos(AX)*X3-sin(AX)*Y3
YR = sin(AX)*X3+cos(AX)*Y3
The AX is the angle of the rotation. What the formulas do can be seen in the illustration below.
This shows how the point (X3,Y3) is rotated AX degrees to the point (XR,YR). This rotation method can be implemented on all three axes giving the resulting formulas :
Around the Z-axis
XR = cos(AZ)*X3-sin(AZ)*Y3
YR = sin(AZ)*X3+cos(AZ)*Y3
ZR = Z3
Around the Y-axis
X3 = cos(AY)*XR-sin(AY)*ZR
Y3 = YR
Z3 = sin(AY)*XR+cos(AY)*ZR
Around the X-axis
XR = X3
YR = sin(AX)*Y3+cos(AX)*Y3
ZR = cos(AX)*Z3-sin(AX)*Z3
The swap between n3 and nR in the middle equation is because we are first rotating the point around the X-axis, then we'll have to use the resulting coordinates from this in the next rotation and so on...
One reminder to the beginner is, all angles are specified to the computer using radians instead of degrees, this means that instead of 360 degrees we'll use 6.2820218... (2 times pi). This means that 1 degree equals to pi/180 radians.
That is all about rotating a 3D point. To rotate an object we'll need to rotate, for example, the endpoints of a line. This is exactly what is done in the next example...