Coding a Sprite
The Sprite
class is simple, storing little more than the sprite's current position, its speed specified as step increments in the x- and y- directions, with imaging managed by ImagesLoader
and ImagesPlayer
objects. The ImagesPlayer
class allows the sprite to show a sequence of images repeatedly since this is how the ant moves its legs.
The Sprite
subclasses, BatSprite
and BallSprite
in BugRunner
, manage user interactions, environment concerns (e.g., collision detection and response), and audio effects. These elements are too application specific to be placed in Sprite
.
The Sprite Constructor
A sprite is initialized with its position, the size of the enclosing panel, an ImagesLoader
object, and the name of an image:
// default step sizes (how far to move in each update) private static final int XSTEP = 5; private static final int YSTEP = 5; private ImagesLoader imsLoader; private int pWidth, pHeight; // panel dimensions // protected vars protected int locx, locy; // location of sprite protected int dx, dy; // amount to move for each update public Sprite(int x, int y, int w, int h, ImagesLoader imsLd, String name) { locx = x; locy = y; pWidth = w; pHeight = h; dx = XSTEP; dy = YSTEP; imsLoader = imsLd; setImage(name); // the sprite's default image is 'name' }
The sprite's coordinate (locx
, locy
) and its step values (dx
, dy
) are stored as integers. This simplifies certain tests and calculations but restricts positional and speed precision. For instance, a ball can't move ...
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.