Game Development Reference
In-Depth Information
The last thing to do in
playBackgroundAudio:
is check if there is no other audio playing and start the
audio by calling
play
on
backgroundPlayer
.
We have looked at how to specify what audio we will want to be able to play during the life of our
game. We have also looked at how to set up a background audio track that plays indefinitely and
with regard to other audio being played. Next, we will see how we play sound effects that are driven
by in-game events.
Sound Effects for In-game Events
At this point, we have done a lot of setup to make sure our application plays audio correctly. We
have also done a little work to make it easy for our game-related classes to play sound effects. In
applyGameLogic (ViewController.m)
if (self.stepNumber%120==0){
[self addActor:[Powerup powerup:self]];
}
for (Powerup* powerup in [self actorsOfType: [Powerup class]]){
if ([powerup overlapsWith:viper]){
[self removeActor: powerup];
[self playAudio: AUDIO_GOT_POWERUP];
}
}
}
In Listing 11-9, we see the task
applyGameLogic
. This task is called once per game step, giving
subclasses of
GameController
a place to specify game-specific logic. In our case, we have things to
do in this task: create
Powerup
actors and check collisions between
Powerups
and the spaceship.
We create a new
Powerup
every 120 steps in the game, or every 3 seconds (120 steps at 60 steps
per second, 120/60 = 3). The newly created
Powerup
is simply added to the scene with the task
addActor:
. The logic that drives where the Powerup is created and how it moves is covered in more
detail in Chapter 12.
The next step in
applyGameLogic
is to test to see if a
Powerup
has collided with the spaceship
viper
. We do this by iterating over each
Powerup
and testing if it collides with the task
overlapsWith:
. If we have a collision, we remove the
Powerup
and call
playAudio:
, passing in
the
NSString AUDIO_GOT_POWER
.
The task playAudio: is shown in Listing 11-10.