Game Development Reference
In-Depth Information
tempMissile.y = player.y;
tempMissile.speed = 5;
missiles.push(tempMissile);
addChild(tempMissile);
var sound:Sound = new Shoot();
sound.play();
}
}
Detecting collisions on multiple types of objects
For Balloon Saw, we had to check to see only if the player touched any of the objects in the
enemies array. For Pixel Shooter, we need to check two types of collisions:
Enemies and missiles
Enemies and the player
We need to do this in two different loops. The first loop tests the enemies array against each
missile by nesting two for loops inside each other. First, we create a for loop that iterates
through all the enemies (backward) and tests each enemy against all the missiles in the missiles
array, iterating those backward as well.
For the collision test, we use the now familiar function hitTestObject() with
if (tempEnemy.hitTestObject(tempMissile)) { }
If we detect a hit, we call createExplosion() (passing the x,y location of the enemy so we know
where to put the explosion on the screen), update the score, and remove the missile and enemy
objects from the screen. The last line, break enemy;, is very important. It sends the execution
back to the enemy: for (var i=enemies.length-1;i>=0;i--) for loop. This enemy: code is called a
label . We use this functionality often to break out of nested loops during collision detection, but it
might be confusing. The basic idea is that this label (or break) methodology allows you to get out
of a loop when necessary. We need to do this because both the tempEnemy and tempMissile
have been removed from the screen and from the enemies and missiles arrays. If we continue in
the nested loop, we will test against values that don't exist any longer, and AS3 will throw an
error. This construct might appear to be like a “go to” statement, but it really is not. It's more like
saying “break out of this nested loop AND get me the next item from the main loop.”
public function testCollisions() {
var tempEnemy:MovieClip;
var tempMissile:MovieClip;
enemy: for (var i:int=enemies.length-1;i>=0;i--) {
tempEnemy = enemies[i];
for (var j:int = missiles.length-1;j>=0;j--) {
tempMissile = missiles[j];
if (tempEnemy.hitTestObject(tempMissile)) {
score++;
scoreText.text = score.toString();
makeExplosion(tempEnemy.x, tempEnemy.y);
removeEnemy(i);
removeMissile(j);
break away;
}
}
}
Search WWH ::




Custom Search