Creating Enemy AI
Making our Moss Giant Move between two waypoints
Since we now have an proper understanding of what Abstract classes are and how different classes and inherit their properties, we can apply these functions to set up our enemy AI system.
Objective: Using the knowledge which we have gained about Abstract classes, we will apply them in our enemy AI system.
Prepping the Enemy AI:
What our enemy AI needs to accomplish is to traverse between two different waypoints while toggling the correct animation (ie. walking & Idle) while also being alert when the player gets into a determined proximity so that our enemy is able to switch to combat mode.
To begin, we will set up the waypoint system. Since all of the enemies are going to have two waypoints to traverse back and forth, adding this feature into the Enemy Abstract class would make most sense.
In the Enemy Abstract class, we are going to create an SerializedField along with adding two transform variables named “point A and point B”.
Once you have that setup in the Abstract class, you will see back in Unity that the script component would ask for two Transform objects. Create two empty game objects and make them as a child of the Moss Giant object. Then drag the two empty game object accordingly to the slots.
Back in the Moss Giant script we are going to create a new private bool which will be a switch that will toggle the movement.
Since we want to start the Moss Giant at “Point A” we will need to set the position to be point A during the start method.
In a new method called “Movement” we are going to create a bool switch which will control the movement between the two transform objects. When the Moss Giant is at point A, the switch will be set to “True” and when the Moss Giant is at point B the switch to be set to false.
The conditions will then tell the Moss Giant to move towards the next target and ping pong back and forth continuously.
Now this method will work, but for better optimization and cleaner script writing, we are going to shorten the Movement method.
To start, we are going to remove the bool switch method and instead use an Vector3 and store the data there for easier access.
The logic behind this method is that the Vectoe3 data is going to swap between Point A and Point B depending on where the Moss Giant is current at. If the Moss Giant is at Point A then the Vector3 named “Current Target” is going to be set to Point B, and vice versa when the Moss Giant is at Point B.
Since the Vector3 data is always updated to the next target, the script for actual movement is going to be much simpler. Just like how we before, the current position is going to be a new Vector3 Move Towards, but the target position is now going to be set to “current Target”. And we only need to write this script once.
Now back in Unity you will see that even with the more optimized script the Moss Giant still moves just like before.