Since we have created modular script “Health” and made Player is capable to shoot in the last article, we will continue to make Enemy have the ability to attack too.
The first thing we need to create is enemy state. Enemy AI should follow the state and doing the proper action, including moving and attacking.
To do this part, we will need to use enum.
Create a public enum list in enemy function script, and also create another variable to store it.
We have created 3 enemy state, and we could use these state to identify what action should the enemy do.
For example, make the enemy can only chasing Player when its state is in Chase.
Now we will use the Attack state to damage our Player.
Before attacking the Player, we need to set a detecting range to make the state of Enemy become “Attack”.
Create a sphere trigger collider to Enemy.
Inside Enemy script, create both OnTriggerEnter() and OnTriggerExit(). These 2 will be used to set the state of Enemy.
Now the Enemy would into Attack mode when Player is in range.
Attack time delay
Also in Update(), create an if statement to make enemy would only attack Player when is in state Attack.
Now we would make Enemy has an attacking time delay.
The attacking method is under Update(), which means it would be called every frame. If Enemy would damage 10 points to Player per attack, Player might be eliminate immediately when got caught by Enemy.
To prevent that, we need to design an attacking time delay to Enemy.
We will need to float to do this part.
The first float would be the time gap between 2 attacks, and the 2nd float would be a record to memorize the time when Enemy attacked.
Now we can slow down the attacking time with “Time.time”.
We use “Time.time” to locate the current time and make it compares with
_nextAttack float time. If the current time is greater than
_nextAttack, that means it is allowed to attack.
To attack, called Damage() method from Player script and pass 10 points to it. After that,
_nextAttack would be current time plus the time gap we set as
_attackDelay. By that time, “Time.time” is no longer greater than
_nextAttack, and it would wait after 1.5 seconds to proceed the next attack.
That is all for Enemy to proceed attack. Play and test it!