On the last post of our lwjgl series, we saw how to draw a triangle. Now, lets learn how to make our triangle rotate around the Z axis.
The first thing we need is to use a different shader so that we may pass the modelView
matrix to the shader and then use the shader to update the vertex positions.
While the identity shader just passed on the vertex position, the flat shader multiplies the vertex position as a matrix passed by a unifor, called mvpMatrix
. Thats exactly what we need. Let's change the code on the initGL method to do that
shader = GLShaderFactory.getFlatShader();
Next, on the render()
method, we need to pass the modelView matrix as a uniform to the shader. The first step is creating the variables to hold the matrix:
float[] modelViewMatrix = new float[16]; float[] translationMatrix = new float[16]; float[] rotationMatrix = new float[16];
Now, lets fill the matrix. We don't want to move the triangle in the scene at this moment, so, lets create the translation matrix filled with zeroes
Math3D.translationMatrix44f(translationMatrix, 0.0f, 0.0f, 0.0f);
For the rotation matrix, let's rotate it around the Z
axis.
Math3D.rotationMatrix44(rotationMatrix, angle, 0.0f, 0.0f, 1.0f);
The angle variable has been created with class scope and is updated every time the render()
method runs.
Now, we need to multiply our matrices and use it as a uniform in our shade.
Math3D.matrixMultiply44(modelViewMatrix, translationMatrix, rotationMatrix); FloatBuffer buff = BufferUtils.createFloatBuffer(16); buff.put(modelViewMatrix); buff.flip(); shader.setUniformMatrix4("mvpMatrix", false, buff);
After multiplying, we need to create a FloatBuffer
to add the shader as a uniform. Then, all we need is to call the setUniformMatrix4
on the shader instances and we are all set.
Thats it for rotation a triangle. You can also change this code to rotate it around other axis or move it around the scene.
Again, all the code is available at http://code.google.com/p/opengl-superbible-java