Using the Sprite Batcher Class

Let's incorporate the TextureRegion and SpriteBatcher classes in our cannon example. I copied the TextureAtlas example and renamed it SpriteBatcherTest. The classes contained in it are called SpriteBatcherTest and SpriteBatcherScreen.

The first thing I did was get rid of the Vertices members in the screen class. We don't need them anymore, since the SpriteBatcher will do all the dirty work for us. Instead I added the following members:

TextureRegion cannonRegion; TextureRegion ballRegion; TextureRegion bobRegion; SpriteBatcher batcher;

We now have a TextureRegion for each of the three objects in our atlas, as well as a SpriteBatcher.

Next I modified the constructor of the screen. I got rid of all the Vertices instantiation and initialization code, and replaced it with a single line of code:

batcher = new SpriteBatcher(glGraphics, l00);

That will set out batcher member to a fresh SpriteBatcher instance that can render 100 sprites in one batch.

The TextureRegions 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, l6, l6); bobRegion = new TextureRegion(texture, 32, 32, 32, 32);

No surprises there. 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) { GLl0 gl = glGraphics.getGL(); gl.glClear(GLl0.GL_COLOR_BUFFER_BIT); camera.setViewportAndMatrices();

gl.glEnable(GLl0.GL_BLEND);

gl.glBlendFunc(GLl0.GL_SRC_ALPHA, GLl0.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 our sprites to the GPU and render everything.

0 0

Post a comment