Feature Highlight: Creating “Eyes” for AI Characters
There are a number of reasons why you might want to your AI characters to have an eyesight behavior. A common use case for this would be anytime you want the enemies in your game to be able to detect the player as it crosses in front of them. Let’s take a look at a simple way to set this up.
I’ll caveat that this method is not the most accurate representation of human eyesight, which can be done much better using raycasting for precise calculations. This is however probably the easiest method and will do the trick in many use cases.
In game logic, what is eyesight really? Well, it’s the ability to detect a collision when an object enters the approximated field of view of whichever object is your viewer, be it a security camera, guard, axe wielding orc or whatever you are working with. In my case, I am working with a set of patrolling security guards with flashlights and the intended behavior is that if the player steps in front of a guard or intersects his flashlight illumination, the player will be “caught” and the game will end.
Here’s a quick hack to create eyesight for these guards. We can create simple cube game objects, place them in a large rectangle in front of our guard’s eyes to act as the collision area, and then remove their mesh renderers to make them invisible.
We can then use the green frames here which represent the box collider to create our eyes — if you cross through this green plane you have been spotted. We set the box colliders to trigger mode and then in our code we can trigger our endgame cutscene with the ontriggerenter() method.
It might look a little funny behind the scenes, but the end result will be a perfectly reasonable AI vision mechanic for our player.
The colliders are set to the approximate length and width of the flashlight beam to give the player a decent sense of the danger zone.
Now we can add the getting caught behavior that happens on collision. We add a new “Eyes” C# script to each of these vision zone gameobjects and implement the OnTriggerEnter code there:
We grab a handle to our game over cutscene game object which is set to play on awake, and set the object active on collision which runs the scene.
Just like that, our game over condition is all set up! In the next guide I’ll cover how to set up a similar behavior for our panning security cameras. See ya there!