In which we give our Walking Enemy the means to attack us
Making our “Walking Enemy” attack the player-character is fairly straightforward.
To start with, the attack itself. This will be fundamentally similar to the player’s laser-attack, but instead of using an indefinitely-long ray we will use a limited-length (in fact, quite short) line-segment, thus creating a “melee attack”.
The detection of hits is once again pretty much the same as in the case of the player: sort the collision-queue, take the first hit (if any), and if that hit was on a GameObject, have that object take damage.
But where the player-character has the attack be controlled by the player’s input, the Walking Enemy will control its attack via its “runLogic” method.
Previously, we had the following in the “runLogic” method of “WalkingEnemy”:
We’ll now add to this a bit:
If the enemy is far from the player, and isn’t playing its attack animation, it’s allowed to move. Furthermore, it resets its attack -waiting and -delaying timers.
If it’s near to the player, it stops moving. If the attack-delay timer is active–that is, it’s attacking, and waiting for the point at which an attack “lands”–it runs that timer down. When the timer runs out, it checks the collision-queue for a hit, and if one’s detected, it applies damage. On the other hand, if the attack-wait timer is active–that is, it’s between attacks, waiting to start an attack–it runs that timer down. When the timer runs out, it starts an attack, and sets the attack-delay timer.
The result looks like this:
And finally, as with the player-character, there’s a bit of cleanup to do:
And that’s it! If you run the game now, you should find that our WalkingEnemy not only chases the player, but attacks when in range, too!
This is all very well and good, but right now all those hits and collisions don’t have much effect. To start with, let’s add some visual feedback: beam-impacts, hit-flashes, and a bit of UI…