Coding a Sprite


Defining a Sprite

A general-purpose Sprite class is hard to design since many of its features depend on the application and the gaming context.

For example, a sprite's on-screen movement greatly depends on the type of game. In Tetris, Breakout, and Space Invaders (and many more), the sprite moves within the gaming area while the background scenery remains stationary. In some of these games, the sprite may be unable to move beyond the edges of the panel, while in others it can wrap around to the opposite edge. In side-scrolling games, such as Super Mario, the sprite hardly moves (perhaps only up and down); instead the background shifts behind it.

A sprite must monitor the game environment, for example, reacting to collisions with different sprites or stopping when it encounters an obstacle. Collision processing can be split into two basic categories: collision detection and collision response, with the range of responses being application specific. Many varieties of collision detection exist: a sprite may be represented by a single bounding box, a reduced size bounding box, or several bounding areas. Examples of each are shown in Figure 11-3 where the bounding regions are the dashed boxes around the pigeon and donkey.

Figure 11-3. Three types of collision detection


A single bounding box is simple to manipulate but prone to inaccuracy. The reduced bounding box is better, but choosing a suitable reduction factor is difficult. The greatest accuracy can be achieved with several boxes for each sprite at the expense of additional calculations.

Sometimes a 2D sprite will have a z-coordinate (or z-level) that dictates its drawing position (or order) on screen, which the user perceives as depth. For instance, if two sprites have the same z-level, then they'll be unable to move past each other, so they will collide. However, a sprite with a smaller z-level is conceptually "in front" of a sprite with a larger z-level, so can pass by without collision. Sprites are drawn in decreasing z-level order, so sprites in the foreground appear in front of those further back.

The visual appearance of a sprite typically changes over time in response to important events (e.g., being shot out of the sky) or by cycling through a series of images (e.g., moving its arms and legs as it walks about). Associated audio effects (e.g., a gunshot sound) may be triggered by events, or played periodically.



Killer Game Programming in Java
Killer Game Programming in Java
ISBN: 0596007302
EAN: 2147483647
Year: 2006
Pages: 340

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net