The Alien SpriteA 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 about in an inefficient manner due to the lack of any path planning, but this behavior is satisfactory (and fast) in a scene with few obstacles.
calcTurn( ) deals with seven possible positional relationships between the alien and the robot, which can be understood by referring to Figure 18-7. Figure 18-7. Possible angles between the alien and robotThe alien begins by facing along the positive z-axis, toward the user's viewpoint. The rotation (stored in rotAngle) is calculated relative to that starting angle so the rotation change from the previous orientation can be obtained by subtraction. The start of headTowardsTourist( ) contains this code: double rotAngle = calcTurn( getCurrLoc( ), ts.getCurrLoc( )); double angleChg = rotAngle-currAngle; doRotateY(angleChg); // rotate to face tourist currAngle = rotAngle; // store new angle for next time The tourist may be in any of the four quadrants marked in Figure 18-7, it may be on the positive or negative x-axes (i.e., with a zero z value), or may be at the same spot as the alien; altogether, there are seven possibilities.
The possibilities for rotAngle are shown in Table 18-1.
These choices are encoded in calcTurn( ) as a series of if tests after calculating xDiff and zDiff (the x-axis and z-axis distances between the two sprites). The calculations for quadrants (1) and (4) and quadrants (2) and (3) could be combined since the signs of the x and z locations are implicit in the values for xDiff and zDiff. |