O'Reilly logo

Killer Game Programming in Java by Andrew Davison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required