Creating Health and Damage
Next up, let’s take a look at how we can go about creating a health and damage mechanic within the game. We could just go back towards an interface, but let’s take a look at another method that could be used to create health, and take it away from our objects. Within our health script, we are going to define a couple things:
When we attached our script to our objects that require health, we can then adjust the values of them further there. This will allow us to attach the script to breakable objects, like boxes, as well as the enemy or player:
Next, we need to adjust our shoot method so that when it hits an enemy, it will take away it’s health, and after so much damage has been dealt, we will destroy the object:
We apply the null check so that we don’t create errors upon hitting objects that do not have a health value.
Now, we shall test it within the game to see if it properly damages our enemy unit:
Now that we have our player able to damage the enemy unit charging for us, let’s get to work on create the method in which the enemy will damage our player.
First, let’s look at how we can create a state method to use within our game so that we can set up multiple states for our enemy to be in rather than just a chase and attack mode:
With this, we are creating a finite state machine that we can use to switch between different states the enemy can go into:
From here, we are just going to start by having the enemy enter into an attack state when it reaches the player, and because the enemy is no longer in the chase state, it will stop moving when it reaches the player. Once the player leaves the range of the collider on the enemy, it will resume chasing our player around the map:
Now, as for implementing a damage part to the player, we will use a cooldown system that will allow for the player to not die in an instant:
With this, we can determine how long we want it to be between our attacks. Now, let’s see how this looks within the game:
Now that we know this works, we are just going to quickly clean up the code a little in the update so that we aren’t just filling it up with if statements. Instead, let’s use a switch statement to switch between the different states our enemy can be in:
Now that we have put in place some health and damage to our game, we can look towards the next part of the game creation.