Playing sound effects
Adding sound effects to our game is a challenge for several reasons:
- Effects must only occur once:
We'll be adding a sound effect for jumping (boing!) and want to make sure that it only happens one time. Fortunately, we have something for that already, our state machine! We can use RedHatBoyContext
to play a sound when something happens, something like this (don't add it yet):
impl RedHatBoyContext { ... fn play_jump_sound(audio: &Audio) { audio.play_sound(self.sound) } }
This leads directly into our second challenge.
- Playing audio on transitions:
We want to play the sound at the moment of transition, but most transitions won't play a sound. Remember our state machine uses transition
to transition from one event to another, and while we could pass in the audio there it would only be used...