Game Development Reference
In-Depth Information
position, size, and texture region. The sprite batcher will be our magic
ingredient to get rid of multiple draw calls and matrix operations per object.
These concepts are highly interconnected and will be discussed next.
The TextureRegion Class
Since we've worked with texture regions already, it should be straightforward to figure out what
we need. We know how to convert from pixel coordinates to texture coordinates. We want
to have a class where we can specify pixel coordinates of an image in a texture atlas, which
then stores the corresponding texture coordinates of the atlas region for further processing
(for example, when we want to render a sprite). Without further ado, Listing 8-16 shows our
TextureRegion
class.
Listing 8-16. TextureRegion.java; Converting Pixel Coordinates to Texture Coordinates
package
com.badlogic.androidgames.framework.gl;
public class
TextureRegion {
public final float
u1, v1;
public final float
u2, v2;
public final
Texture texture;
public
TextureRegion(Texture texture,
float
x,
float
y,
float
width,
float
height) {
this
.u1 = x / texture.width;
this
.v1 = y / texture.height;
this
.u2 =
this
.u1 + width / texture.width;
this
.v2 =
this
.v1 + height / texture.height;
this
.texture = texture;
}
}
The
TextureRegion
stores the texture coordinates of the top-left corner (
u1
,
v1
) and bottom-right
corner (
u2
,
v2
) of the region in texture coordinates. The constructor takes a
Texture
and the top-
left corner, as well as the width and height of the region, in pixel coordinates. To construct a
texture region for the cannon, we could do this:
TextureRegion cannonRegion =
new
TextureRegion(texture, 0, 0, 64, 32);
Similarly, we could construct a region for Bob:
TextureRegion bobRegion =
new
TextureRegion(texture, 32, 32, 32, 32);
And so on and so forth. We can use this in the example code that we've already created, and
use the
TextureRegion.u1
,
v1
,
u2
, and
v2
members for specifying the texture coordinates of the
vertices of our rectangles. But we won't need do that, since we want to get rid of these tedious
definitions altogether. That's what we can use the sprite batcher for.