Who goes there !?— Giving sight to AI
In this quick article I am going to go over a simple collider sight system for AI sight.
The first step is to create the object that we will use as our field of vision, for this I have created a cube and attached it to my guard, ensuring the cubes collider is a trigger.
Next step is to create a sight script. On this script add we are going to add an on trigger enter and on trigger stay method. The on trigger enter function will check if the collision is with a player and if so, assign to a global variable to the current game time (Time.time), I will call this “sightedStartTime:”. The on trigger stay event will check if difference between the sighted time and current time is greater than 0.75 seconds. This gives the player a little bit of leeway when playing.
If the player is sighted for the right amount of time we now need to let the game know it needs to take action, for this stealth game it means game over. I have created an action (OnGameOver) that the player, guards and game manager (to call cut scenes) can subscribe to. This will be called on the OnTriggerStay method.
On the player and guard script I have created a function GameOver. This function will be called when the OnGameOver action is called, this just disables our objects.
On our GameManager script this action will set the game over cutscene to active.
We just need to make sure our player is tagged as player and our eyes object has a rigid body attached.
Last, we can test our new feature.
That’s all for now.