How to let your AI See!
This tutorial covers how to make it so that your AI guards can see the player if they pass in front of them. There are multiple other ways to do this like using a raycast. For this tutorial you will use a cube in front of the guard as a trigger for when they see the player. Add a cube to the first guard and adjust its size so that it stretches from the front of the guard as far as you want him to see. Make sure the cubes collider is set as Is Trigger. Turn off the mesh renderer so that it is not visible. Make sure you add a rigid body to them so that they will be able to use OnTriggerEnter.
Next, rename it to something like Eyes. Duplicate it and add it to each of your guards. Reposition it for each guard as necessary.
Next, create an Eyes script that you will attach to each of your Eyes objects you just created. You will not need the Start or Update functions so you can delete those. Add a variable of GameObject type for the game over cutscene. Assign it in the Unity Editor for each set of Eyes you have. Add the OnTriggerEnter function. Check if the other collider has the Player tag. Then use SetActive from the game over cutscene variable to set it to true which will activate the cutscene.
[SerializeField] private GameObject _gameOverCutscene;private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
_gameOverCutscene.SetActive(true);
}
}
Now your guards are able to “see” the player and start the game over cutscene whenever they see the player.
-Chris