Video Game Math: Matrices
What are matrices?
Matrices is plural for a matrix - which is a collection of numbers represented in a grid, very similar to a table or spreadsheet. They look a little like this.
By itself, that collection of numbers is mostly meaningless, but if you use them to assign values - such as the coordinates of an object – they become very handy containers and they can be used for a lot of convenient things.
This is especially true in the world of 3D programming. Every model in a 3D game if made up of a number of “tris” or “polys” – triangles or polygons – and in a modern game a character might have tens of thousands of them. Each has a number of vertices (the “corners”) – 3 for tris and 4 for polys – that we need to keep track of, that’s a lot of data!
A matrix makes a nice storage container, with each column being a new vertex and the three rows corresponding to the vertex’s x, y and z positions in 3D space.
A big challenge is how to manipulate those vertices to do something you want. A great example is turning. If you stand up with your arms outstretched and think about your body as a series of points – one at each joint for example – and try to turn, you’ll notice that the joints toward the center of you, such as your neck, travel less distance than the joints further out from the center, such as individual fingers. Consequently, during your turn your head moved a lot less distance than your outstretched hands did.
Why are matrices important?
While we can definitely write code to calculate all those positions, having to iterate through each point and calculate it is relatively inefficient, both on the “writing code” level and the mathematical level. Due to a quirk in how matrices work, we can multiply our points matrix by another matrix called a “transformation matrix” and a computer can solve that quite easily and quickly – plus the function can be reused for other cool applications like reflection (if the model needs to be reflected over water or a mirror), scaling (making a bigger/smaller version of a model) or for calculating things like drift and orbit.
Knowledge of matrices is so crucial to anyone working in 3D programming that many programming books dedicate an entire section at the front of the book to matrices – you really can’t even get started until you understand how the math works.