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