Game Development Reference
In-Depth Information
The
TextureRegion
s get initialized in the
resume()
method, as they depend on the
Texture
:
@Override
public void
resume() {
texture =
new
Texture(((GLGame)game), "atlas.png");
cannonRegion =
new
TextureRegion(texture, 0, 0, 64, 32);
ballRegion =
new
TextureRegion(texture, 0, 32, 16, 16);
bobRegion =
new
TextureRegion(texture, 32, 32, 32, 32);
}
No surprises here. The last thing we need to change is the
present()
method. You'll be surprised
how clean it's looking now. Here it is:
@Override
public void
present(
float
deltaTime) {
GL10 gl = glGraphics.getGL();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
camera.setViewportAndMatrices();
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glEnable(GL10.GL_TEXTURE_2D);
batcher.beginBatch(texture);
int
len = targets.size();
for
(
int
i = 0; i < len; i++) {
GameObject target = targets.get(i);
batcher.drawSprite(target.position.x, target.position.y, 0.5f, 0.5f, bobRegion);
}
batcher.drawSprite(ball.position.x, ball.position.y, 0.2f, 0.2f, ballRegion);
batcher.drawSprite(cannon.position.x, cannon.position.y, 1, 0.5f, cannon.angle,
cannonRegion);
batcher.endBatch();
}
That is super sweet. The only OpenGL ES calls we issue now are for clearing the screen,
enabling blending and texturing, and setting the blend function. The rest is pure
SpriteBatcher
and
Camera2D
goodness. Since all our objects share the same texture atlas, we can render them
in a single batch. We call
batcher.beginBatch()
with the atlas texture, render all the Bob targets
using the simple drawing method, render the ball (again with the simple drawing method), and
finally render the cannon using the drawing method that can rotate a sprite. We end the method
by calling
batcher.endBatch()
, which will actually transfer the geometry of your sprites to the
GPU and render everything.
Measuring Performance
So how much faster is the
SpriteBatcher
method than the method you used in
BobTest
? Let's
take the
BobTest
code and rewrite it using your new OpenGL ES classes. We add an
FPSCounter
to the code, increase the number of targets to 100 and set the maximum number of sprites the