I’ve gone into this a bit in a previous article, but today let’s address the code.
When you are creating AI for your game, you may want them to simulate sight so as to give the feeling that they can see what is going on around them. This is of course all smoke and mirrors as are most things in the world of game development, but if done correctly, it can make your game feel ALIVE!
The concept of creating a cone of vision is about as simple as the code needed to implement it. Which is good news to all of you non-programmers out there just trying to prototype/flesh out their game.
To create a line of sight you can use Raycasting, which is a little more complex, or you can use colliders. I will make an article on Raycasting to see your targets eventually, but today it’s just colliders.
You will need to create an empty child object under your AI and add a collider of some form to it. Then stretch it out in front of your AI according to your preferences. These are the boundaries that determine what they can and cannot see.
If you are wanting to do multiple lines of sight to represent the peripheral vision or something else the do so now.
Make sure you set your colliders to “Trigger”.
Now for the script. Create a new C# script and attach it to the new game object you made that contains the colliders for the AI’s cone of vision.
For my game, I activated a cutscene depicting a game over sequence after the player is detected. But you could use this same reasoning to trigger combat, dialogue, or whatever after the enemy sees the player.
If you created extra cones of vision for the peripheral detection, then you just need to repeat the steps above but on a separate game object than the first and trigger a different state for your AI such as begin searching for the player, or whatever you are wanting.