Phaser for Beginners

Playing sounds

The idea is to store all sounds in an array and then play the right song according to what’s going on in the game. We are going a property in playGame object called soundArray. It’s defined as an empty array and will be visible only inside playGame object.

We declare it this way:

In the same playGame object, inside create method once we called placeTiles and we add the audio if the player selected the option to play with sound, that is if playSound is set to true.

A small change to create method:

To insert elements into an array we always used push method but you can also declare items one by one assigning a value for a given index, like I did in these latest lines of code., volume) adds a new audio file to the sound manager. key is the name we gave to the sound, while volume is playing volume. It ranges from 0 to 1 where 1 means maximum volume.

Now that the sounds are preloaded and ready to be played, it’s time to insert our first sound into showTile method. This will be played when a tile is shown:

Obviously before playing any sound effect we must check for playSound to be true.

play() method plays a sound.

Play the game, pick tiles and you should hear the sound effect. In the same way it’s easy to add sounds to checkTiles method, one to be played when the player made a successful match and one to be played when there wasn’t any match.

Sounds gave the game a deeper experience, but there’s still a missing key feature, which is the one we all play for: the score.

Download Source


Next Tutorial →

Showing the score

← Previous Tutorial

Preloading sounds