This article will show how to set up an Enemy base class that the other enemies will inherit. One advantage of using inheritance is that it prevents you from writing the same or similar code multiple times in different scripts. All three enemies are inheriting from the same script for their movement.
All three enemies are inheriting from the same script for their movement. We will go over the setup for the Moss Giant, but the other enemies are set up the same way.
Enemy Base Class
We will make the Enemy base class abstract so that we can force the inheriting scripts to implement methods. For the Enemy script, we are going to need several variables to control the movement behavior.
- The speed the Enemy will move from one point to the other.
- The points the Enemy will move between.
- The current point that the Enemy is moving towards.
- A reference to the Animator, so we can change the animation.
- A reference to the Sprite Renderer so we can flip the sprite.
In Start, we grab the references and set the current point to point A. We also enforce any inheriting scripts to have an Update method by making it abstract.
The Flip method flips the sprite on the x-axis to face the current point based on whether it is to the left or right of the Enemy.
The Movement method first checks if the idle animation is playing by grabbing the information about the current state of the base layer (0) from the Animator and check if it is named Idle, then end the method. Next, we check the distance from the Enemy to the Current Point to see if it is less than or equal to 0.1 and then change the Current Point to the other point, call the Flip method, and play the idle animation. If the Enemy is not near the Current Point, we move it towards the Current Point.
The Moss Giant is set up similarly to the Player in a previous article. It has a Box Collider 2D set as a Trigger and the Sprite as a child with an Animator component. The two points are empty GameObjects.
The MossGiant script inherits from Enemy and calls Movement in Update.
The Moss Giant moves between the two points and plays the idle animation upon reaching an end.