Posted on April 26, 2018
Matrix Transformations
This entry is not about a game project but more about game development. I am dedicating this post to one of the major math concepts being used in game programming and computer graphics in general: Matrix Transformations.
The first demo implements 2D matrix transformations from scratch in HTML5 Canvas. It is a top-down tilemap where you can move the character, a red square, around it. Besides that, there are some sliders below to modify the transformation.
Here is the link to the demo if you want to take a look at the code:
https://games.jahepi.net/2dtransformations/index.html
Last but not least, the second demo implements a 3D rotation matrix. It rotates the Z axis (XY Plane), Y axis (XZ Plane), and X axis (YZ Plane) where a cube resides.
For reference, this is how a 3D rotation on the X, Y, and Z axes works. We have in total 3 planes, we are going to start with the XY plane, where we rotate the Z axis. It is a clockwise rotation in a left-handed system.
Here is a graphic representation of how the XY plane looks, and we are going to set the values in the matrix:
XY PLANE
The basis vectors X and Y were rotated some amount of degrees. As you can see, the hypotenuse length is 1, so the sides of the right triangle correspond to the ratio of the trigonometric functions cosine and sine.
We set the values in our matrix (Z axis rotation):
[ x y z]
[cos(0), cos(0), 0][x]
[-sin(0), sin(0), 0][y]
[ 0, 0, 1][z]
Now we are going to do the same with the two remaining planes.
YZ PLANE
We set the values in our matrix (X axis rotation):
[ x y z]
[1, 0, 0][x]
[0, cos(0), sin(0)][y]
[0, -sin(0), cos(0)][z]
XZ PLANE
We set the values in our matrix (Y axis rotation):
[ x y z]
[cos(0), 0 -sin(0)][x]
[0, 1, 0)][y]
[sin(0), 0, cos(0)][z]
Here is the demo where we apply the transformations to the vertices that build up the cube:
Here is the link to the demo if you want to take a look at the code: https://games.jahepi.net/3drotation/index.html
If you want to learn more about this topic, I recommend reading 3D Math Primer For Graphics And Game Development. Even though this book does not focus solely on matrix transformations, it is a great resource of knowledge if you want to delve deeper into the math behind 2D and 3D programming.