Skip to content

Instantly share code, notes, and snippets.

@markeahogan
Created February 27, 2024 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markeahogan/d6e07a70c6c36390e18ddd619faee849 to your computer and use it in GitHub Desktop.
Save markeahogan/d6e07a70c6c36390e18ddd619faee849 to your computer and use it in GitHub Desktop.
Adds extension methods for Unity's AudioSource class for volume and rolloff calculation based on distance. The CalculateVolumeAtDistance method computes the volume of the audio source at a given distance. CalculateRolloffMultiplier calculates the rolloff factor based on the distance and the AudioSource's rolloff mode.
public static class AudioSourceExtensions
{
public static float CalculateVolumeAtDistance(this AudioSource source, float distance, float volumeRolloffScale = 1)
{
var rolloff = CalculateRolloffMultipler(source, distance, volumeRolloffScale);
return source.volume * Mathf.Lerp(1, rolloff, source.spatialBlend);
}
public static float CalculateRolloffMultipler(this AudioSource source, float distance, float volumeRolloffScale = 1)
{
switch (source.rolloffMode)
{
case AudioRolloffMode.Logarithmic:
return distance < source.maxDistance ? source.minDistance * (1f / (1f + volumeRolloffScale * (distance - 1))) : 0;
case AudioRolloffMode.Linear:
return Mathf.InverseLerp(source.maxDistance, source.minDistance, distance);
case AudioRolloffMode.Custom:
var curve = source.GetCustomCurve(AudioSourceCurveType.CustomRolloff);
return curve.Evaluate(Mathf.InverseLerp(source.minDistance, source.maxDistance, distance));
default:
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment