Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to set proper "audio" volume based on distance (x,y)

Tags:

algorithm

i'm developing a game. How can i "fade in" the audio volume for a sound, based on the "distance" of a sprite from the current render scene ? Suppose i've a world:

WIDTH_WORLD = 10000
HEIGHT_WORLD = 10000

Current Scene  
xCurrent = 800   ( + Width Res. = 800 + 1024 = 1824)  
yCurrent = 400   ( + Height Res. = 400 + 768 =... )

Far Sprite
xSprite = 7000 
ySprite = 3000 

What is a good algorithm to "calculate" audio volume (and maybe left/right pan channel ratio) ? Thanks in advance!

like image 619
stighy Avatar asked Oct 13 '22 21:10

stighy


1 Answers

Total Volumn

  • There are several approaches for the attenuation of the volume. E.g. you could use a linear damping function, like volume = max( 0, max_volume - max_volume/max_distance * distance ), or a function with inverse distance fall off, like volume = min( max_volume, max_volume / distance ).

Balance Ratio

  • Again, there are several approaches to realize an adequate functionality. In your case, you could say, if the object is at or beyond the left screen border, pan to the left, if the object is at or beyond the right screen border, pan to the right, otherwise use an interpolation function, e.g. balance = (object_x-camera_x) / screen_half_width with values between -1: left, +1: right, and 0: center.

When combining these approaches you have to think about what is suitable for your case: For example only damp the volume if the object is out of screen bounds, what ever...

like image 86
Flinsch Avatar answered Nov 15 '22 08:11

Flinsch