Game Development Reference
In-Depth Information
Now let's assume we are instantiating 100
Bob
instances, like this:
Bob[] bobs =
new
Bob[100];
for(
int
i = 0; i < 100; i++) {
bobs[i] =
new
Bob();
}
To render each of these
Bob
instances, we'd do something like this (assuming we've already
cleared the screen, set the projection matrix, and bound the texture):
gl.glMatrixMode(GL10.GL_MODELVIEW);
for(
int
i = 0; i < 100; i++) {
bob.update(deltaTime);
gl.glLoadIdentity();
gl.glTranslatef(bobs[i].x, bobs[i].y, 0);
bobModel.render(GL10.GL_TRIANGLES, 0, 6);
}
That is pretty sweet, isn't it? For each
Bob
instance, we call its
update()
method, which will
advance its position and make sure it stays within the bounds of our little world. Next, we
load an identity matrix into the model-view matrix of OpenGL ES so we have a clean slate. We
then use the current
Bob
instance's x and y coordinates in a call to
glTranslatef()
. When we
render the Bob model in the next call, all the vertices will be offset by the current
Bob
instance's
position—exactly what we wanted.
Putting It Together
Let's make this a full-blown example. Listing 7-13 shows the code with comments interpersed.
Listing 7-13. BobTest.java; 100 Moving Bobs!
package
com.badlogic.androidgames.glbasics;
import
javax.microedition.khronos.opengles.GL10;
import
com.badlogic.androidgames.framework.Game;
import
com.badlogic.androidgames.framework.Screen;
import
com.badlogic.androidgames.framework.gl.FPSCounter;
import
com.badlogic.androidgames.framework.gl.Texture;
import
com.badlogic.androidgames.framework.gl.Vertices;
import
com.badlogic.androidgames.framework.impl.GLGame;
import
com.badlogic.androidgames.framework.impl.GLGraphics;
public class
BobTest
extends
GLGame {
public
Screen getStartScreen() {
return new
BobScreen(
this
);
}
class
BobScreen
extends
Screen {
static final int
NUM_BOBS
= 100;
GLGraphics glGraphics;