In this lesson, we see the benefits of using a 3rd party 3D matrix library for performing 3D matrix transformations.
In a previous lesson we saw how to apply a 3D transformation matrix to animate 3D forms. In that we were manually creating a matrix by filling a float32 array with specific values. I create a couple of rotate functions for you, and you may have created some other transformation functions on your own. The main issue with how we were doing that though, was that you could only apply a single matrix at a time, thus you could only achieve a single transformation.
In order to achieve multiple transformation such as rotating and translating, rotating and scaling, or rotating on multiple axes, you need to create multiple matrices and multiply them together. Now rather than wading through the intricacies of matrix multiplication and building out all the possible functions that we would need to do all these full transformations, I think it would be much more efficient to use a library that someone has already created for this purpose. There are a few out there built specifically for webgl.
I'll add in a vertex count variable and set it to 30, so we can draw 10 triangles. Down in createVertices, I will have this vertices array start at empty then loop through vertexCount a number of times, and add three random values to the array, for random x, y, and z coordinates. Jumping down to draw, I'll make sure that the call to drawArrays gets the vertex count value, then I'll get rid of the rotation stuff I had before, including those functions. Now I'll use gl-matrix to do the transforming. We'll start by rotating on the Z axis again.
The way gl-matrix works is you that you call a static method on the mat4 object, passing various values. It's set up so you can transform a matrix, assigning the transform values to another matrix, or assign them back to the same matrix. So for rotateZ we pass in the matrix you want to receive the transform values, then the source matrix, then the angle to rotate. For now, we'll pass in the matrix we create for both the first and second parameters, and an angle of 0.01.
Because we're transforming the same matrix in place in each frame, that next frame will rotate it an additional 0.1 radians and so on, and we should get continuous rotation. Now like before, we need to get the location for the transform matrix uniform, and assign the matrix to that uniform. We run that, and we do have some triangles rotating around. Still very flat though, but the great thing now is that we can very easily to multiple transformations.
I'll just add another call saying mat4.rotateY, run that, and we're starting to see something that really does look like 3D. Let's add in some X rotation for kicks. Of course we still just have a single color, no lighting and no perspectives, so everything's still kind of just blends together. We have a lot of work to do, but we are getting there.