Chapter 11. Sprites

A game’s active entities are often encoded as sprites . A sprite is a moving graphical object, which may represent the player (and so respond to key presses and mouse actions) or may be driven by “intelligent” code in the game. The Sprite class developed in this chapter holds a sprite’s position, its speed (coded as incremental steps in the x and y directions), and it uses the image classes (ImagesLoader, ImagesPlayer) from Chapter 6 to manage its graphical presence. Sprite’s subclasses add user and environmental interactions and audio effects. The coding of these classes is helped by specifying them first with UML statecharts.

Tip

Many elements are utilized from earlier chapters: the animation framework from Chapters 2 and 3, the image loader classes from Chapter 6, and the audio loaders from Chapter 8.

Bats, Balls, and Sprites

The BugRunner example allows the user to control a sprite in the shape of an ant. The objective is to move the sprite left and right across the base of the gaming pane to stop falling ball sprites from hitting the floor. Figure 11-1 shows BugRunner in action.

Tip

The screenshot is a little misleading because the futuristic cityscape and the flying car are part of the game’s background image and aren’t active elements in the game. The gameplay components are the ant at the bottom of the screen and the falling yellow and red ball near the center of the panel.

The ant is controlled with the arrow keys or by clicking with the mouse. The left arrow ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.