Game Development Reference
In-Depth Information
And that is all there is to do. We just eliminated a lot of drawing methods simply by buffering
pre-transformed vertices in a float array and rendering them in one go. That will increase our
2D sprite-rendering performance considerably, compared to the method we were using before.
Fewer OpenGL ES state changes and fewer drawing calls make the GPU happy.
There's one more thing we need to implement: a
SpriteBatcher.drawSprite()
method that can
draw a rotated sprite. All we need to do is construct the four corner vertices without adding
the position, rotate them around the origin, add the position of the sprite so that the vertices
are placed in the world space, and then proceed as in the previous drawing method. We could
use
Vector2.rotate()
for this, but that would introduce additional function call overhead. We
therefore reproduce the code in
Vector2.rotate()
, and optimize where possible. The final
method of the
SpriteBatcher
class looks like Listing 8-18.
Listing 8-18. The Rest of SpriteBatcher.java; a Method to Draw Rotated Sprites
public void
drawSprite(
float
x,
float
y,
float
width,
float
height,
float
angle,
TextureRegion region) {
float
halfWidth = width / 2;
float
halfHeight = height / 2;
float
rad = angle * Vector2.
TO_RADIANS
;
float
cos = FloatMath.
cos
(rad);
float
sin = FloatMath.
sin
(rad);
float
x1 = -halfWidth * cos - (-halfHeight) * sin;
float
y1 = -halfWidth * sin + (-halfHeight) * cos;
float
x2 = halfWidth * cos - (-halfHeight) * sin;
float
y2 = halfWidth * sin + (-halfHeight) * cos;
float
x3 = halfWidth * cos - halfHeight * sin;
float
y3 = halfWidth * sin + halfHeight * cos;
float
x4 = -halfWidth * cos - halfHeight * sin;
float
y4 = -halfWidth * sin + halfHeight * cos;
x1 += x;
y1 += y;
x2 += x;
y2 += y;
x3 += x;
y3 += y;
x4 += x;
y4 += y;
verticesBuffer[bufferIndex++] = x1;
verticesBuffer[bufferIndex++] = y1;
verticesBuffer[bufferIndex++] = region.u1;
verticesBuffer[bufferIndex++] = region.v2;
verticesBuffer[bufferIndex++] = x2;
verticesBuffer[bufferIndex++] = y2;
verticesBuffer[bufferIndex++] = region.u2;
verticesBuffer[bufferIndex++] = region.v2;