Game Development Reference
In-Depth Information
horizontal difference in tile locations and store it in the horizontalDiff variable and the vertical
difference with the vericalDiff variable.
We will use the absolute value Math function to compare the horizontalDiff and the
verticalDiff . We want the predator to move in the direction where the number of tiles between
the player and the tank is the lowest One problem crops up when we try to compare directions,
because we can't adequately compare negative values that result from the simple compare math
against positive values. For instance, here are the steps the code needs to take for the example
comparison in Figure 7-6:
1.
The prey is in horizontal column 2 and vertical row 8.
2.
The predator is at horizontal column 4 and vertical row 6.
3. predator.currCol minus prey.currCol equals 2 .
4.
If the prey 's vertical row is 8 and the preditor 's is 6, then pred.currRow minus
prey.currRow equals -2.
5.
The difference really is simply 2 in both directions. The negative number results from
the order in which we do the subtraction.
When we compare these to see which is smaller (the direction where the prey is closest to the
predator), we must use the Math.abs (absolute value) function to ensure we are comparing the
numbers properly. We do this because -2 will always be less than 2 unless we compare with the
absolute value function, which ignores the sign of the integer. In looking at tile location
differences, 2 and -2 are equivalent. Both indicate the same distance difference between
predator and prey . Again, we only care about the number of tiles difference between the
locations of the sprite; we don't care about the sign of the result of the difference calculation. The
negative would cause this function to not work half the time.
When we have selected to move horizontally or vertically, we then need to choose which direction
(left or right for horizontal and up or down for vertical) for the enemy tank to move.
First, we'll take a look at the code and then we'll discuss the major points from the function.
The chaseObject function
Here's the code for the chaseObject function:
private function chaseObject(prey:TileByTileBlitSprite,
predator:TileByTileBlitSprite):void {
//trace("chase");
if (prey.currentRegion == predator.currentRegion) {
moveDirectionsToTest = [];
var horizontalDiff:int = predator.currCol - prey.currCol;
var verticalDiff:int = predator.currRow - prey.currRow;
if (Math.abs(verticalDiff) < Math.abs(horizontalDiff)) {
if (verticalDiff >0) {
//trace("AI UP");
moveDirectionsToTest.push(MOVE_UP);
moveDirectionsToTest.push(MOVE_DOWN);
Search WWH ::




Custom Search