How to make sound fade in/out based on the distance from the source of the sound maybe like a club in a game and if you get further the music volume will get lower
To calculate the volume level needed based on how far away an object is from the player, follow the following steps:
(player
= player listening to the sound, and ball
= object making sound)
- Find the XY difference
var diffX = Math.abs(player.x-ball.x);
var diffY = Math.abs(player.y-ball.y);
- Using the XY difference, you can find the distance from the player to the ball using the pythagorean theorem.
var distance = Math.sqrt( Math.pow(diffX,2) + Math.pow(diffY,2) )
- Now that we know the distance you’ll need to get a value for the volume. The farther the distance, the smaller you want the volume to be. There are two ways you could do this.
- Mathod 1: Create a variable for the maximum volume and subtract from it the distance
var max = project.width/2; // Adjust the max if necessary
var volume = Math.max(max-distance,0);
- Method 2: You can divide 1 by the distance. The greater the distance, the shorter the volume.
var num1 = 1; // Increase the 1 if necessary
var volume = 10000*(1/distance);
Here’s an example project:
test.wick (2.3 KB)
I didn’t have a volume asset to test with, but I did create a volume variable that increases/ decreases slowly based on the distance.
Next, you can use code from Jovanny’s music player project to control/ set the volume of your sound assets based on the distance two objects are apart (you should also use Math.min to set a limit on the volume).
2 Likes