Hi!
I’m totally green, but I was very intrigued by Phaser 3. And after the first review I really liked this smart engine
I bought a book HTML5 Cross Platform Game Development Using Phaser 3 by Emanuele Feronato. I started working on my game and I am thinking about some functionality.
Is it possible to put a sound assigned to some object or to some 2D space? The effect of this would be that the player, when approaching this object, hears the sound louder.
Hi @Tom, I guess that 2D spatial sound would be possible with Phaser. You would need to calculate the distance between the player and the object (the sound source), normalize that distance to a 0-1 range and apply that value to the sound volume, and maybe adjusting the pan based on the sign of the distance too. Sound perception is not linear, our ears work logarithmically so maybe you may need to apply a log() function somewhere to make the volume change feel more real.
Hey Tom, you definitely can. One way that comes to mind is simply increasing volume based on distance, so in an update loop or on an onPlayerMove event, you could have something like:
let distanceThreshold = 400; //This is the max distance from the object. Any farther and no sound is played.
let distanceToObject = Phaser.Math.Distance.Between(player.x, player.y, soundObj.x, soundObj.y);
let normalizedSound = 1 - (distanceToObject / distanceThreshold);
sound.volume = normalizedSound;
Also, as Jackfreak said, sound perception isn’t linear, so you could add a curve to the volume to make it seem more realistic. In order to do this, simply add an easing function to the normalizedSound. So, sound.volume = normalizedSound; turns into sound.volume = Phaser.Math.Easing.Sine.In(normalizedSound);