I want to trigger an event if an enemy (or player) can hear a sound generated from other enemy/player.
How to implement a sound detection system ?
Thanks
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It only takes a minute to sign up.
Sign up to join this communityI want to trigger an event if an enemy (or player) can hear a sound generated from other enemy/player.
How to implement a sound detection system ?
Thanks
When it comes to AI actors reacting to noises, then most games do not actually jack into the audio system. The reason is that it is far too unpredictable from a gameplay perspective.
Enemies reacting to noises is something you usually focus on in stealth-based games. And stealth-based games often play more like puzzle games than action games. This also applies to the level design. In order to create a good puzzle, you need to know exactly how your pieces interact. If you use a real audio engine with occultation, dampening, reflections etc. (which Unity won't do out-of-the-box, but there are ways to do these things) and use audio clips as inputs which can change during development, then your AI actors behavior becomes quite unpredictable. This makes it very difficult to design enemy encounters which play out the way you want them to.
It also makes the game very unintuitive to play. In most games, players develop a feeling for the hearing range of the enemies and use that information to plan their strategies. But with a realistic audio engine, hearing ranges can be very dependent on environmental details. It will become very difficult for the player to estimate what the AI opponents will hear and what they won't hear. This can become very frustrating.
For that reason you should create an own audio detection system which is separated from the actual audio system. When the player performs an action which generates a sound the AI actors are supposed to react to, then use Physics.OverlapSphere
(or Physics2D.OverlapCircle
if your game uses 2d physics) to find any AI actors in range and inform them of the player's position and the nature of the sound. Your AI should then measure the distance to the player and decide what to do with that information.
If you don't want AI actors to be able to hear the player through walls, you can use a Physics.Linecast
/ Physics2D.Linecast
to detect obstructions. Increase the distance accordingly when your AI actor decides whether or not it reacts to that input.
From Unity's Audio Listener API it seems like there is no way to check if the camera hears a sound or not.
The only solution I can think, is to control manually the volume of a specific AudioSource
based on its distance from the camera. So that you can get that AudioSource
's volume to see if the sound is actually audible or not.