Game Development Reference
In-Depth Information
attribute that we don't specify. Most of these defaults can be set directly. For example, if we
want to set a default color for all vertices that we draw, we can use the following method:
GL10.glColor4f(
float
r,
float
g,
float
b,
float
a)
This method will set the default color to be used for all vertices for which one wasn't specified.
The color is given as RGBA values in the range of 0.0 to 1.0, as was the case for the clear color
earlier. The default color OpenGL ES starts with is (1,1,1,1)—that is, fully opaque white.
That's all the code we need to render a triangle with a custom parallel projection—a mere 16
lines of code for clearing the screen, setting the viewport and projection matrix, creating an NIO
buffer in which we store our vertex positions, and drawing the triangle! Now compare that to the
six pages it took us to explain this to you. We could have, of course, left out the details and used
coarser language. The problem is that OpenGL ES is a pretty complex beast at times and, to
avoid getting an empty screen, it's best to learn what it's all about rather than just copying and
pasting code.
Putting It Together
To round this section out, let's put all this together via a nice
GLGame
and
Screen
implementation.
Listing 7-5 shows the complete example.
Listing 7-5. FirstTriangleTest.java
package
com.badlogic.androidgames.glbasics;
import
java.nio.ByteBuffer;
import
java.nio.ByteOrder;
import
java.nio.FloatBuffer;
import
javax.microedition.khronos.opengles.GL10;
import
com.badlogic.androidgames.framework.Game;
import
com.badlogic.androidgames.framework.Screen;
import
com.badlogic.androidgames.framework.impl.GLGame;
import
com.badlogic.androidgames.framework.impl.GLGraphics;
public class
FirstTriangleTest
extends
GLGame {
public
Screen getStartScreen() {
return new
FirstTriangleScreen(
this
);
}
The
FirstTriangleTest
class derives from
GLGame
, and thus has to implement the
Game.getStartScreen()
method. In that method, we create a new
FirstTriangleScreen
, which
will then be called frequently to update and present itself by the
GLGame
. Note that when this
method is called, we are already in the main loop—or rather, the
GLSurfaceView
rendering
thread—so we can use OpenGL ES methods in the constructor of the
FirstTriangleScreen
class. Let's have a closer look at that
Screen
implementation.