Adding sound to sprite animation frames

Hey there, phaser 3 user here. :slight_smile:

I’m wanting to add some sound to an animation, I can see how it can be accomplished using the key data of the animation using

psuedo code

if(sprite.anims.currentAnim.key === 'walking') {
    this.sound.play('sound-example')
}

How can I execute a sound based on which frame the sprite animation is at?

I thought maybe using conditionals on the frames itself would be appropriate instead of a simple event trigger, but honestly I’m not sure. I can’t figure out which is the most appropriate method in the animation class, even when I’m looking at the phaser 3 docs.

If there is a better approach or if someone could push me in the right direction, please let me know.

Any help would be much appreciated!

Thanks.

I found a solution. I can use the setTimeout function, and set the milliseconds to the milliseconds per frame. I’m not sure how efficient this is, so if anyone knows a more efficient way to do this, please let me know.

The frame rate set to 1. 1000 ms per frame. I set the setTimeout function based on the ms.

Heres some of the code:

psuedocode

function create() {

var config = {
    key: 'walk',
    frames: this.anims.generateFrameNumbers('mummy'),
    frameRate: 1,
    yoyo: false,
    repeat: 0
  };

this.input.keyboard.on('keydown_SPACE', function (event) {
    sprite.anims.play('walk');
    setTimeout(playSound, 1000);
    setTimeout(playSound, 4000);
    setTimeout(playSound, 10000);
    setTimeout(playSound, 12000);
  });
}

function update() {
  var debug = [
    'msPerFrame: ' + sprite.anims.msPerFrame
  ];
}

https://labs.phaser.io/view.html?src=src\animation\animation%20repeat%20event.js

2 Likes