Shooting zombies is fun and all, but it’s like shooting a dead fish in a barrel if they’re not going to fight back, so let’s give them an attack system that will access the players Health script.
To make things simple, when the enemy gets within a certain distance of us, they’ll inflict damage. We can do that by giving our zombie a spherical collider; Voila! we’ve created that radius! Don’t forget to enable ‘is Trigger’!
Let’s make the radius a little bigger by making it 1 unit.
Once the enemy is within range, we want it to stop and inflict damage.
Before we do anything, let’s compartmentalize our code a little. Let’s get all of our movement code out of Update() into its own CalculateMovement() function:
Now we’ll want to figure out a way to stop moving while the enemy is attacking. While we could use a boolean, we can create a state machine for our zombie which will have different states like idle, attack, move, etc.
We first create our state machine by using an Enum
As you can see, our enum contains a variety of different ‘states’ our zombie will be in. Next, we’ll create a variable to hold our current state.
We’ll Serialize it so we can keep track of it in the editor. We’ll also set a default state of Chase. It does much now since none of the states are actually programmed yet, but it will make sense later!
So currently, we only want our enemy to move when its in chase mode:
and if they’re near the player, they’ll go into attack mode but if the player escapes, they’ll go back into chase:
Let’s give it a try!
GREAT SUCCESS! Our enemy now chases our player, and you can see it’s switching states depending on how close the player is, awesome!
Now when our enemy enters the attack state, we want them to damage our player, and then wait for a moment and then attack again. We’ll need to create a cooldown system which is not unlike the thruster cooldown in the space shooter.
First, we’ll need to cache our player health, let’s create a holder:
and for our cooldown, we’ll create a couple of variables:
_attackDelay will be 1.5 seconds, and _nextAttack is -1 so the first attack will launch automatically since any Time is larger than -1.
In Update(), we’ll then put in a check for the attack state:
So when we enter attack mode, we’ll initiate our cooldown system:
As said before, Time will always be over -1, so the enemy will immediately attack, so let’s finally call the damage code.
So Boom! The player suffers 10 hitpoints (after a null check), and then the _nextAttack gets reset to the current time with the _attackDelay added, which is 1.5 seconds. So if the player stays in range, the enemy will attack once 1.5 seconds have passed.
Let’s test it!
Huzzah!!! Our player is now getting hit for 10 damage every 1.5 seconds! Our zombies are now officially dangerous!