The Texture Region 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 that then stores the corresponding texture coordinates for the atlas region for further processing (e.g., when we want to render a sprite). Without further ado, Listing 8-16 shows our TextureRegion class.

Listing 8-16. Converting Pixel Coordinates to Texture Coordinates package;

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 could 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 do that, since we want to get rid of these tedious definitions altogether. That's what we'll use the sprite batcher for.

Was this article helpful?

0 0

Post a comment