How to calculate audio volume based on logarithmic rolloff and distance from Listener?

I know how to get the value for both linear and custom rolloff based on distance from the Listener, however, not logarithmic.

Does anyone have a formula we could use to calculate it?

Not sure if this really old thread has the answer, but I couldn’t make heads or tails of what they’re saying. They didn’t specify which rolloff mode they were talking about.

Thanks,
Brian

This seems to work:

// The distance at which the volume starts to reduce
float referenceDistance = 1.0f;
float distance = Vector3.Distance(transform.position, listener.position);

// version 1
audioSource.volume = initialVolume * Mathf.Pow(Mathf.Max(distance, referenceDistance) / referenceDistance, -rolloffFactor);

// version 2
float ratio = distance / referenceDistance;
audioSource.volume = initialVolume * (1.0f / (1.0f + rolloffFactor * Mathf.Log(ratio)));
1 Like

Thank you for the reply! But what are initialVolume and especially rolloffFactor? I assume I can read the Min Distance of the Audio Source as reference distance.

9543136--1347847--upload_2023-12-22_0-4-26.png

Hi!

Sorry, just getting back to work after the holidays :slight_smile:

In this case, initialVolume is "the volume you would set the audio source to if you weren’t handling distance attenuation yourself. Since we’re using AudioSource.volume to control the actual level of the source, we need that additional variable to store the distance-agnostic [0, 1] volume value.

The rolloffFactor represents how quickly the volume diminishes with the distance.

Finally, referenceDistance is the kind of pivot point used for these calculations, simply put it’s the distance from which the sound starts to dim.

Thanks!
Rolloff factor is still confusing to me. AFAIK, the only thing we can change in Logarithmic rolloff is min distance and max distance. If we change or add any key in the graph, it will instantly switch to “Custom” and it no longer logarithmic. And for Custom I can already calculate the volume correctly. So are we supposed to somehow calculate rolloff factor from min/max distance?

Reference distance still sounds like Min Distance to me.

When you implement yourself volume decay, rolloff factor is really a knob to tweak. From the tests I’ve made, values between 1 and 2 give good results. Trust your ears!

Cool! Assuming I added a new Audio Source, set it to Logarithmic and didn’t change a thing, would 1 be correct?

I think so!
Like I (actually, many others before me…) said: trust your ears :wink: