Created
February 27, 2024 16:44
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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