In this lesson, you will learn how to simulate realistic NPC hearing by implementing spherical trigger volumes that detect sound-emitting events within your game world.
The Concept of Auditory Zones
While Line of Sight (LOS) handles what an NPC sees, auditory trigger zones represent what an NPC hears. Instead of checking constant raycasts, we use a SphereCollider set to isTrigger attached to the NPC. This creates a "hearing radius." When a player performs a noisy action—like running on metal or firing a weapon—we broadcast a "Sound Event" that triggers the NPC’s perception logic.
Implementing the Trigger
To keep your AI reactive, you don't want the NPC to react to everything—only significant noises. We use a component on the player (or the object making noise) to "emit" the sound, and the NPC's OnTriggerEnter method to catch it.
public class AuditorySensor : MonoBehaviour
{
// The NPC's perception range
public float hearingRadius = 10f;
void OnTriggerEnter(Collider other)
{
// Check if the object entering is a "NoiseSource"
if (other.CompareTag("NoiseSource"))
{
// Inform the Blackboard/State Machine that a sound was heard
Debug.Log("Sound detected at: " + other.transform.position);
// Trigger transition to 'Investigate' state
}
}
}
Integrating with AI Logic
Once the OnTriggerEnter event fires, you should pass the location of the sound source to your Blackboard System. Your NPC's State Machine should then transition from an Idle or Patrol state to an Investigate state. By setting the NavMeshAgent destination to the other.transform.position captured by the trigger, your NPC will move toward the source of the noise.
Crucially, ensure your sound trigger zones are scaled appropriately. A small footstep might only trigger a tiny radius, while a loud explosion should temporarily scale the SphereCollider size to alert NPCs from much further away. This layering allows for nuanced stealth gameplay where player behavior directly dictates NPC awareness.
Key Takeaway: By using spherical trigger volumes as hearing proxies, you can bridge the gap between environmental actions and NPC state transitions, creating reactive AI that feels alive.