Game Development Reference
In-Depth Information
for (Asteroid* asteroid in asteroids){
for (Bullet* bullet in bullets){
if ([bullet overlapsWith:asteroid]){
[bullet decrementDamage: self];
asteroids_destroyed++;
[asteroid doHit:self];
[self incrementScore: [asteroid level]*10];
break;
}
}
if ([asteroid overlapsWith:viper]){
[viper decrementHealth: [asteroid level]*2];
Shield* shield = [Shield shieldProtecting:viper From: asteroid];
[self addActor:shield];
asteroids_destroyed++;
[asteroid doHit:self];
}
}
In Listing 12-14, we see the first part of the task
doCollisionDetection
where we handle the
interaction concerning Asteroids. The first thing we do in this task is to get a reference to all of
the different
Actors
we are going to need to interact with. Once we have reference to all of the
Asteroids
,
Bullets
, and the
Viper
, we can start testing to see if there are collisions. Inside the
outermost loop in Listing 12-14, we start by testing to see if each
Asteroid
overlaps with each
Bullet
. If they do, we have the bullet decrement the Asteroid's damage, which usually removes
the Asteroid from the game, but more on that later. We also record that we have destroyed another
Asteroid before calling
doHit;
on the
Asteroid
. Lastly, we increment the score.
In Listing 12-14, after we have considered the relation between each
Asteroid
and
Bullet
, we check
to see if the
Asteroid
is overlapping the
Viper
. If it is, we decrement the health of the
Viper
and
add a
Shield
to the scene. The
Shield
is an
Actor
that is just decoration and has no game function
beyond that; it looks like a shield went up to protect the spaceship.
Let's look at the rest of the
doCollisionDetection
task and understand how the rest of the inter-
Actor relationships are handled. The task continues in Listing 12-15.
Listing 12-15. BeltCommanderController.m (doCollisionDetection, part 2)
for (Bullet* bullet in bullets){
if ([[bullet source] isKindOfClass:[Saucer class]]){
if ([viper overlapsWith: bullet]){
[viper decrementHealth: [bullet damage]];
Shield* shield = [Shield shieldProtecting:viper From: bullet];
[self addActor:shield];
[self removeActor:bullet];
break;
}