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

The Alien Sprite

A TimeBehavior object drives AlienSprite's chasing behavior by calling AlienSprite's update() method periodically. update() uses the alien's and robot's current positions to calculate a rotation that makes the alien turn to face the robot. Then the alien moves toward the robot. Once the alien is sufficiently close to the robot, an exciting message is printed to standard output (this is, after all, just a demo).

update() is defined as follows:

    public void update()
    // called by TimeBehaviour to update the alien
    { if (isActive()) {
        headTowardsTourist();
        if (closeTogether(getCurrLoc(), ts.getCurrLoc()))
          System.out.println("Alien and Tourist are close together");
      }
    }

headTowardsTourist() rotates the sprite then attempts to move it forward:

    private void headTowardsTourist()
    {
      double rotAngle = calcTurn( getCurrLoc(), ts.getCurrLoc());
      double angleChg = rotAngle-currAngle;
      doRotateY(angleChg);   // rotate to face tourist
      currAngle = rotAngle;  // store new angle for next time
      if (moveForward())
        ;
      else if (moveLeft())
        ;

      else if (moveRight())
        ;
      else if (moveBackward())
        ;
      else
        System.out.println("Alien stuck!");
    }

AlienSprite extends TourSprite and uses the movement and rotation methods defined in that class.

A complication with the chasing behavior is how to deal with obstacles. If a move is blocked by an obstacle, then the move method (i.e., moveForward(), moveLeft()) returns false. headTowardsTourist() tries each method until one succeeds. This may lead to the sprite moving ...

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