Game Development Reference
In-Depth Information
means that it detects objects touching based on an invisible box that represents the extreme
bounds of any pixel in the image. See Figure 1-7.
Figure 1-7. Bounding boxes colliding (boxes shown for illustration only)
For square objects, bounding box collision works fine, but for objects that have curves, spikes,
and so on, it doesn't really work at all. We used bounding box collision detection for this game
because it is quick, but later in this topic, we will show you multiple other ways to detect in a more
precise manner collisions (including using pixel-perfect collision detection, which would be more
appropriate for this game). By the way, there is also a MovieClip.hitTestPoint() method that
tests if an object has reach a particular (x,y) coordinate on the screen, but we will leave that one
for your own personal explorations.
This function iterates backward through the enemies array, testing each one to see if they have
collided with player. If they do collide, we update the score by 1 point, and increase the text value
in the TextField by one, and then remove the balloon from the enemies array with
enemies.splice(i,1) and from the screen using removeChild(tempEnemy) .
The other interesting thing we do in this function is play a sound. We create an instance of the
Pop sound from the library as sound and then call sound.play() every time a balloon is popped.
This is the simplest way to play a sound. It works, but this method lacks any way to control the
volume and other properties of the sound that is played. We will discuss other ways to manage
sounds as you progress through this topic.
public function testCollisions() {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int=enemies.length-1;i>=0;i--) {
tempEnemy = enemies[i];
if (tempEnemy.hitTestObject(player)) {
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
Search WWH ::




Custom Search