Texture Regions Sprites and Batches Hiding OpenGL ES

Our code so far for the cannon example is made up of a lot of boilerplate, some of which can be reduced. One such area is the definition of the Vertices instances. It's tedious to always have seven lines of code just to define a single textured rectangle. Another area we could improve is the manual calculation of texture coordinates for images in a texture atlas. Finally, there's a lot of code involved when we want to render our 2D rectangles that's highly repetitive. I also hinted at a better way of rendering many objects than having one draw call per object. We can solve all these issues by introducing a few new concepts:

■ Texture regions: We worked with texture regions in the last example. A texture region is a rectangular area within a single texture (e.g., the area that contains the cannon in our atlas). We want a nice class that can encapsulate all the nasty calculations for translating pixel coordinates to texture coordinates.

■ Sprites: A sprite is a lot like one of our game objects. It has a position (and possibly orientation and scale), as well as a graphical extent. We render a sprite via a rectangle, just as we render Bob or the cannon. In fact, the graphical representations of Bob and the other objects can and should be considered sprites. A sprite also maps to a region in a texture. That's where texture regions come into. While it is tempting to combine sprites with game directly, we keep them separated, following the Model-View-Controller pattern. This clean seperation between graphics and mode code makes for a better design.

■ Sprite batchers: A sprite batcher is responsible for rendering multiple sprites in one go. To do this, the sprite batcher needs to know each sprite's 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; we'll discuss them next.

0 0

Post a comment