Monday, July 27, 2015

Playing a Sound with Phaser

Work on the Amphibian.com 404-page game continued even this weekend. Among other things, I added the logic to catch the ball being kicked out-of-bounds. In that case, a whistle is blown, play stops momentarily, and the ball gets tossed back into play from the sidelines.

The weird part is that there don't seem to be any examples on the Phaser site that demonstrate audio. Fortunately it wasn't that big of a deal. Audio resources are handled in much the same way as image resources and the documentation is fairly clear.

In my preload function, I added a line to load the .mp3 of the whistle sound. Just like with images, you specify a key so you can reference them later. I used "whistle" as my key.

function preload() {

    // "normal" images
    game.load.image('frog', 'images/frog.png');
    game.load.image('goal', 'images/goal.png');
    game.load.image('net', 'images/net.png');

    // spritesheet for ball animation
    game.load.spritesheet('ball', 'images/ball_animation.png', 45, 45);

    // tilemap and tiles
    game.load.tilemap('map', 'images/ground.json', null, Phaser.Tilemap.TILED_JSON);
    game.load.image('tiles', 'images/field-tiles.png');

    // sounds
    game.load.audio('whistle', 'audio/whistle.mp3');

}

Then in my create function, I create a Phaser.Sound object by calling game.sound.add("whistle"). This references the key "whistle" that I made in preload, so this object will be in control of the .mp3 file specified there.

var whistle;

function create() {

    // ... create all the other stuff ...

    whistle = game.sound.add("whistle");

}

Finally, in the update function I check to see if the ball has traveled beyond the bounds of the soccer field. I removed the collideWorldBounds setting from the ball as well, so it won't bounce back into play when it hits the world bounds on the other side of the line.

if (mode === PLAY_MODE
        && (ball.position.x < 40 || ball.position.y < 50
            || ball.position.x > 1640 || ball.position.y > 800)) {

    whistle.play();

    tossBall(ball.position.x, ball.position.y); 

}

To play the sound I just call the play() function on my whistle object to play the sound. All parameters to the play function are optional and the defaults make sense for basic sounds.

I think the sound adds a nice touch. I'm not going to do background music or anything in the game, but I will probably add a few more sounds for things like scoring a goal or maybe when the game starts.

Remember that the full source code to the game is available on GitHub! Updates roughly every other day!

I need to work on the logic for the opponent a little more. It is far from perfect. Much like today's comic.

Amphibian.com comic for 27 July 2015

No comments:

Post a Comment