How to let your AI See!
Objective: Give your enemies the ability to see and detect your player!
Sneaking passed patrolling enemies is a whole lot more impressive when the enemies in question can see in front of them. This tutorial is all about creating ‘eyes’ for your patrolling enemies and creating consequences for the player being seen.
One of the most accurate ways to recreate the human eye sight is using raycasting, however, we have dealt with raycasting a lot. There for, we are going to use a different method. We are going to create an object that acts as a trigger in front of the enemies however far away we want them to be able to see.
Right click the enemy you want to see, select 3D object, select cube.
This will create a cube on top of your character.
Rename the cube ‘Eyes’ and raise the cube to around chest height.
This needs to go in front of your character.
To make the object longer you can scale up the Z axis.
Bring the object back to the front of your character and turn off the Mesh Renderer.
Under the Box Collider mark ‘Is Trigger’ true so objects can pass through it.
We need to add a rigidbody and turn off the gravity.
Now that the object is set, create a script to give the object functionality.
This is a trigger script so delete every thing inside. What do we want to happen when the enemy sees our player? For this tutorial I want to trigger the game over cutscene. So we need a variable to store the cutscene.
With this script being a trigger script we need to add an on trigger enter method.
If the collider detects an object with the tag player we want to start the cutscene. In other words we want to set the game over cutscene to true.
This is all there is to it. Now when you player enters your enemy’s line of sight they will be detected. Feel free to experiment with your trigger reactions and even the enemies sight line, and I’ll see you in the next tutorial.