3D Survival FPS Game
Creating Enemies with Manual AI
There are several method when creating enemy AI including third party assets to using Unity’s own pathfinder system, but for our situation we are going to be scripting from scratch just to understand how the enemy AI script functions.
Prepping the Enemy:
For now we are going to be using placeholders as the enemy objects. I used a 3D cube and extended the Y scale value to 3. Then I created a new material to apply to the enemy so they can be colored.
We are also going to add a “Character Controller” to the enemy game object since the AI would be using the same functionality as the player. Finally we are going to finish by created a new prefabs folder and making the enemy game object into a prefab.
Understanding the Enemy Function:
First we must understand that the enemy game object functions very similar to the player game object, therefore they will be both relying on the Character Controller function. The main difference between these two would be the target and movement. The Enemy would either be moving within its preset location until the player is within range then the enemy would be moving towards the player.
For now we will focus on the first part which is making the Enemy follow the player. Start by creating a new C# script called “Enemy AI”. Just like with the player script we are going to follow the same procedure as we did with the player, which is giving the same global variables such as speed, gravity, and access to the Character Controller.
In the start method we are going to gain access the character controller and also the Transform for the player. We will need the transform position of the player since that will be our “target” to follow for the enemy.
Next we are going to create a new method called “Movement” and just like with the player script, we are going to start with an IF statement checking whenever the enemy object is grounded.
Within the IF statement we are going to make the direction variable = the target position — the current enemy position. We are also going to normalize the direction variable because we don’t want the enemy object to suddenly teleport to the player but instead moving gradually. Finally we are going to add some rotation to the enemy object since it would look quite weird if the enemy isn’t facing the player as they approach them. Along with that we are also going to add in the final local variable “Velocity” which is going to be the direction multiplied by the speed variable.
To finish off the Movement method we are going to add gravity, so whenever the enemy is within the air, they will be coming back down. Then we are going to add in the character controller Move function to move our enemy.
Back in Unity you are going to drag the script into the Enemy game object if you haven’t so already, then you can test out the newly functional enemy which will follow the player anywhere.