开发者

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

i'm developing a game. How can i "fade in" the audio开发者_JAVA百科 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!


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...


Use the distance (Dsquared = xdist^2 + ydist ^2) as a scaling factor to downscale your volume. Invert this distance squared value to apply directly to your volume (volume falls off as a square of distance, and distance is easily calculated as a squared value anyway).

Left / right channel ratio is done simply by defining two different points for the left and right channels (to the left and right, respectively, of your render location), perform the above calculation, and find the ratios of your channels that way. Because the above calculation is just a sum of two squares, it's very computationally simple.


Well, the volume of a sound degrades as the square of the distance from the sound source, so that would give you a good place to start.

Knowing what library you are using for your game would be helpful though - many game libraries will have this sort of functionality built in already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜