## Matrices Again

Remember when we briefly talked about matrices earlier? We discussed how matrices can encode transformations such as translations (moving stuff around), rotations, and scaling. The projection matrix we use to project our vertices onto the projection plane encodes a special type of transformation: a projection.

Matrices are the key to solving our previous problem more elegantly. Instead of manually moving our vertex positions around by redefining them, we simply set a matrix that encodes a translation. Since the projection matrix of OpenGL ES is already occupied by our orthographics projection matrix we specified via gl0rthof(), we use a different OpenGL ES matrix: the model-view matrix. Here's how we could render our model with its origin moved to a specific location in eye/world space:

gl.glMatrixMode(GL10.GL_M0DELVIEW); gl.glLoadIdentity(); gl.glTranslatef(200, 300, 0); vertices.draw(GL10.GL_TRIANGLES, 0, 6);

We have to first tell OpenGL ES which matrix we want to manipulate. In our case that's the model-view matrix, which is specified by the constant GL10.GL_M0DELVIEW. Next we make sure that the model-view matrix is set to an identity matrix. Basically we just overwrite anything that was in there alreadyâ€”we sort of clear the matrix. The next call is where the magic happens.

The method glTranslatef() takes three arguments: the translation on the x-, y-, and z-axes. Since we want the origin of our model to be placed at (200,300) in eye/world space, we specify a translation by 200 units on the x-axis and a translation by 300 units on the y-axis. As we are working in 2D, we simply ignore the z-axis and set the translation component to zero. We didn't specify a z-coordinate for our vertices, so these will default to zero. Adding zero to zero equals zero, so our vertices will stay in the x-y plane.

From this point on, the model-view matrix of OpenGL ES encodes a translation by (200,300,0), which will be applied to all vertices that pass through the OpenGL ES pipeline. If you refer back to Figure 7-4, you'll see that OpenGL ES will multiply each vertex with the model-view matrix first and then apply the projection matrix. Up until this point, the model-view matrix was set to an identity matrix (the default of OpenGL ES). It therefore did not have an effect on our vertices. Our little glTranslatef() call changes this, and will move all vertices first before they are projected.

Of course, this is done on the fly; the values in our Vertices instance do not change at all. We would have noticed any permanent change to your Vertices instance as by that logic the projection matrix would have changed it already.

Of course, this is done on the fly; the values in our Vertices instance do not change at all. We would have noticed any permanent change to your Vertices instance as by that logic the projection matrix would have changed it already.

## Post a comment