How I make AI find the player's last location
What i want to do?
In Hotline Miami and OTXO, the enemy “sees” the player and then processes to move to the player location, stay in the location for a few seconds and if nothing happens, back to patrol action.
What do I already have?
Using Top down engine, the enemy in Deadline demo can already patrol around an area and shoot the player if the player stands too close. However, it doesn’t chase the player as well as “find” player's last location. The AIBrain is fairly simple with only three states:
What did I do?
So lucky that Top down engine tools already have the AI last known location function, a move toward Target 2D function and an AI demo that already have the AI that chases the player. These scripts already cover 50% of what i want to achieve, the other 50 is lying in the MoveToward target script. In the AI last known location script, I found this method.
Basically, the SetLastKnownLocation creates a gameObject, whenever the script getting called the newGo gameobject changes its transform depending on the AIBrain Target location. This mechanic makes my job so much easier, now I just need to create a “LastPlayerLocation” gameobject and whenever I need to get the last known position of player, I just simply access the transform in the LastPlayerLocation reference.
Before we continue, there is an issue with MoveTowardsTarget2D script. It is straightforward, easy and NO PATHFINDING implemented, so I need to find a way to make the AI understand what path they need to stay on without bumping into the wall.
Using NavMeshPlus is the answer, the Unity community is so great with various tools. NavMeshPlus allows me to use pathfinding on 2D projects with the same function as 3D ones. I can bake my 2D map
and make some small changes to fit with 2D projects. The next thing to do is create a script to make AI run to the player last location, actually “create” is a little bit exaggeration, the “AIActionPathfinderToTargetLastLocation2D” script I make is mostly the same as AIActionPathfinderToTarget3D script which is already provided by TopDown Engine. I just need to add a variable
and change the line which set the destination for the Pathfinding
to this
The rest of the story lies on how I created the AIBrain. Although it gave me a little headache because there are no visualize way to understand how the AI behavior in play mode, I managed to create an AI that I wanted:
In short, if the AI sees a player, it will mark the player’s last location and move to that location. If a player in the AI shooting range, it will shoot, otherwise after 7 seconds it will move back to its patrol path. It is fully functioning just like how I wanted it to be!
Comments
Post a Comment