I started off by defining an enemy patrol zone. This is an area where an enemy will randomly patrol until they detect the player, when they will then chase and attack the player. I want to stress that this isn't using any of unitys colliders / triggers. This is all calculated by maths and combining a Unity editor script to visualise the area. The cube is there as an obstacle to test the path finding.
My next task was to define an enemy's line of sight to detect the player. My first thought for this was to use a mesh collider, so I modelled a line of sight to use as a mesh collider. (below)
Unfortunately, there is a(nother) bug with Unity, mesh colliders do not detect collisions when another collider is fully within the mesh collider. This should be easily avoidable by checking one check box called "convex", but this only breaks it more.
So I set out in the same way that I did with the patrol area, I ended up defining my own line of sight using maths (lots and lots of maths, so much maths that I started to forget the concept of maths), and drew the area in the scene using another editor script.
The four lines coming from the monkey's eyes are its line of sight, much like the mesh collider. The lines turn red when the enemy detects a player. I also coded in the ability to hide behind objects; an enemy will not see you if you are behind an object.
(an enemy thats detected the player)
The breakdown of the features are:
Enemy's will randomly patrol their zone
The will constantly search for the player
Pre checks ensure that a player will only be detected when they are not behind an object
Enemy will start to chase and attack player when detected
When the player is far enough away from the enemy, the enemy will return to their patrol zone and continue to patrol.
I am extremely happy with my outcome, I believe I have made quite a sophisticated system and it reflects all my learning with c# this year.
HERE'S ALL OF THE AI CODE
ALL OF THE ENEMY SIGHT SCRIPT

No comments:
Post a Comment