New Feature — Adding a new Enemy

Objective: Refactor the code so that we can add different types of enemies that use the same base code

In this article, we will explore the problems I ran into when I introduced the second type of enemy into the game and how I solve this by refactoring the code so that each enemy script inherited code from a base class yet can still behave uniquely.

When creating a base class, EnemyBase, we need to consider what each enemy shares.

At the “Base” level, both of these enemies share, movement speed, firing rate, number of shots, they both die to the player's laser shot,

Uniquely, one fighter moves down the screen and returns from the top whereas the other bounces of the sides.

Creating the EnemyBase class

In the class, I moved everything that was common with each of the enemies in this class, starting with their properties. Noticed that the private scope has been changed to protected. This allows only the class that is inheriting the base class to access these properties.

Then each of the common methods:

Next, I renamed the original Enemy class to Fighter and refactored the code to make use of the EnemyBase class. We start with class inheritance.

Here we can create unique properties and methods for the enemy type but make use of the common properties and methods in the base class.

In the Wave class, we need to change the reference to the EnemyBase array and any references to Enemy throughout the project to EnemyBase.

We can now add as many enemy types as we see fit as long as they inherit the EnemyBase class

If you enjoyed reading this article give me a Clap, also if you would like to see more, “Follow” me, so you may be notified of future releases. You may also send me a message if you need any further help.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store