I'm programming a game with Phaser 3 where I have a moving cart. I added a sound for the cart but it can be heard as soon as the cart is put into motion, regardless of the player's distance from it. I'd like to set the volume of the cart in a way that, if the player is very far from it, the sound will basically be muted, and that its volume will increase/decrease depending on its proximity.
I found this link and tried to apply it to my code, but with no success, so I tried to change it a little bit to see if I could make it work.
What I have in my code now is this:
preload() {
this.load.audio("cartSound", "assets/audios/cart.mp3");
}
startCart1Movement() {
this.startCartSound();
}
startCartSound() {
this.distanceThreshold = 400;
this.distanceToObject = Phaser.Math.Distance.Between(
this.player.x, this.player.y, this.cart1.x, this.cart1.y
);
this.cartSound.setVolume(
1 - (this.distanceToObject / this.distanceThreshold)
);
this.cartSound.play();
}
The startCartSound
function is read in its entirety because if I add at the end a console.log
the computer will read it, but still there is no variation in the cart sound.
Can anyone help me out? Thanks so much in advance.