In this lesson, you will learn how to use physics-based raycasting to detect real-time obstructions between an AudioSource and the AudioListener to dynamically muffle sound.
The Concept of Obstruction
While distance attenuation handles how quiet a sound gets as you move away, obstruction simulates what happens when an object—like a wall or a pillar—comes between the listener and the sound source. In reality, physical barriers absorb high-frequency sound waves, making the audio sound "muffled" or "dull."
Using Raycasting for Sound Pathing
To implement this, we use Physics.Raycast. Every frame (or at a set interval), we cast a line from the AudioSource position to the AudioListener position. If that ray hits a collider, we know the sound is obstructed.
Here is how you might structure a basic detection script:
void Update() {
Vector3 direction = listener.position - source.position;
float distance = direction.magnitude;
// Check if anything is between the source and listener
if (Physics.Raycast(source.position, direction, out RaycastHit hit, distance)) {
// Obstruction detected!
ApplyLowPassFilter(true);
} else {
// Path is clear
ApplyLowPassFilter(false);
}
}
Dynamic Attenuation
When the ray hits an object, you don’t just want to stop the sound; you want to change its quality. The most common way to do this in Unity is by manipulating the AudioLowPassFilter component on your AudioSource. By lowering the cutoffFrequency parameter when an obstruction is detected, you effectively strip away the high-frequency "brightness" of the sound. When the obstruction is cleared, you ramp that value back up to its default (usually 22,000Hz).
This approach turns static sound objects into reactive elements that feel part of the physical world. Instead of the sound simply cutting out, the player hears a realistic, muffled version of the audio, providing critical feedback about the environment's layout.
Key Takeaway: By combining raycasting to detect line-of-sight and an AudioLowPassFilter to dynamically adjust frequency cutoff, you can simulate realistic acoustic muffling caused by physical world obstacles.