Game Development Reference
In-Depth Information
enemies.push(tempEnemy);
}
}
Moving balloons
Another core function of an action game is to move objects on the screen. We will create a
function that controls the movement of all of the objects in the game (except the player, which is
attached to the mouse). While this game only has one set of objects to move (the balloons), this
structure can be (and later, will be) used for multiple types of objects in a single game.
The
moveEnemies()
function loops through the
enemies
array, updating each balloon's
y
position.
Since the balloons are moving up the screen, we subtract the
speed
from each balloon's
y
property. If a balloon has reached a
y
position of -35, we remove it from the
enemies
array and
from the screen using
removeChild()
. Notice that the
for
loop we use counts backward (from
enemies.length-1
to
0
). You will see this logic many times in this topic. Iterating backward
through arrays is a very useful tool in games, especially when you are looping through an array
and possibly removing items from it. If you looped forward and removed items, errors will be
created because the length of the array would change as items are removed from it.
public function moveEnemies() {
var tempEnemy:MovieClip;
for (var i:int = enemies.length-1;i >= 0;i--) {
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35) {
chances++;
chanceText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
Testing collisions between the saw and balloons
Now, we get to the heart of this game—testing to see if any of the objects are touching each
other. A core function of many games is
collision detection
. Collision detection is the process of
testing to see if objects are touching each other and, if so, processing the changes to those
objects. Collision detection is not a single algorithm; it is a whole class of algorithms that are
suitable for different circumstances. For this game, we will be using a very simple version of
collision detection built into AS3.
Here, we get to the good news and the bad news. The good news is that AS3 has the same
functionality of older versions of ActionScript: the
hitTest()
method of
MovieClip
for testing
collisions. It's called
MovieClip.hitTestObject()
now, but it works pretty much the same as the
old
hitTest()
. You pass a reference to another
MovieClip
object to see if there is a collision. In
our game, we test a balloon (represented by
tempEnemy
) to see if it has hit the
player
:
tempEnemy.hitTestObject(player)
. Like its predecessor,
hitTestObject()
is both a blessing and
a curse. It's blessing because it's really easy to implement. It's curse because it doesn't really
work that well for games.
hitTestObject()
uses
bounding box collision detection
, which