Game Development Reference
In-Depth Information
The SpriteBatcher Class
As already discussed, a sprite can be easily defined by its position, size, and texture region (and,
optionally, its rotation and scale). It is simply a graphical rectangle in our world space. To make
things easier, we stick to the conventions, with the position being in the center of the sprite
and the rectangle constructed around that center. Now we can have a Sprite class and use
it like this:
Sprite bobSprite = new Sprite(20, 20, 0.5f, 0.5f, bobRegion);
That would construct a new sprite, with its center at (20,20) in the world, extending 0.25 m to
each side, and using the bobRegion TextureRegion . But we could do this instead:
spriteBatcher.drawSprite(bob.x, bob.y, BOB_WIDTH, BOB_HEIGHT, bobRegion);
Now that looks a lot better. We don't need to construct yet another object to represent the
graphical side of your object. Instead, we draw an instance of Bob on demand. We could also
have an overloaded method:
spriteBatcher.drawSprite(cannon.x, cannon.y, CANNON_WIDTH, CANNON_HEIGHT, cannon.angle,
cannonRegion);
That would draw the cannon, rotated by its angle. So how can we implement the sprite batcher?
Where are the Vertices instances? Let's think about how the batcher could work.
What is batching anyway? In the graphics community, batching is defined as collapsing multiple
draw calls into a single draw call. This makes the GPU happy, as discussed in Chapter 7.
A sprite batcher offers one way to make this happen. Here's how:
ï?®
The batcher has a buffer that is empty initially (or becomes empty after we
signal it to be cleared). That buffer will hold vertices. It will be a simple float
array, in our case.
SpriteBatcher.drawSprite() method, we add four
vertices to the buffer based on the position, size, orientation, and texture
region that were specified as arguments. This also means that we have
to rotate and translate the vertex positions manually, without the help of
OpenGL ES. Fear not, though, the code of your Vector2 class will come in
handy here. This is the key to eliminating all the draw calls.
ï?®
Each time we call the
ï?®
Once we have specified all the sprites we want to render, we tell the sprite
batcher to submit the vertices for all the rectangles of the sprites to the GPU
in one go and then call the actual OpenGL ES drawing method to render all
the rectangles. For this, we can transfer the contents of the float array to a
Vertices instance and use it to render the rectangles.
Note You can only batch sprites that use the same texture. However, it's not a huge problem,
since you'll use texture atlases, anyway.
 
 
Search WWH ::




Custom Search