Challenge: Enemies that avoid your shots
For this enemy, I’ll use the graphic from the Photobashing tutorial:
This particular enemy was quite a challenge to get working right, but here’s a method that I finally found that works pretty well. Originally it used two colliders, but through a bit of compromise, I was able to get it down to one. And we don’t place it on the ship, we place it in front of the ship so we’ll know early that a laser is headed our way!
I gave this enemy an ID of 7. So let’s go into the enemy code and see how it behaves:
Ok, so the enemy just moves down, fires its lasers occasionally, and then respawns at the top when it reaches the bottom. Nothing fancy. The OnTriggerEnter2D Method is where we’ll find this enemys personality:
if the other object has the tag of “Laser”, then we run a check for enemy 7. A new if statement that has variables of _numberOfDodges (int 0) & _numberOfDodgesLimit (int 3) is used here to limit the amount of dodges this enemy can do because it’s just too good at dodging! We’ll only let it dodge 3 shots before it allows itself to get hit.
so here we check to see if the laser hits the BoxCollider2D, we add 1 to number of dodges, and we assign an amount to move to be a unit and a half in the x axis.
We assign the enemies current position to a variable, (we need to do this for when we move to the side using MoveTowards), then we check to see where the laser hit the collider, if the x position of the laser is less than the collider, then it’s left. otherwise, it’s right if it’s greater than.
I found it necessary to introduce a new boolean called ‘haveChosen’ because the check is continuous, by setting a boolean, it will stop immediately once it does one check, and we set it to false. Otherwise, I found the enemy ship to shake and act erratically.
So when the laser enters the hit box, it decides whether to go left or right, when it does, we call a Coroutine called Dodge that will move the enemy, so while the current position of the enemy doesn’t equal to _lerpPos which is the endpoint of the dodge, we’ll assign the vertical y position of the enemy into _lerpPos and slowly move the enemy towards its final destination of _lerpPos. yield return 0; makes unity wait only 1 frame. and the enemy will continue to move until it reaches the final dodge point, where the code will drop out of the while loop and return null and finally end the coroutine.
Finally, when we reach the limit of dodges, we destroy our enemy! Let’s see it in action!
Grrr! He’s working as annoyingly as we wanted him! Tomorrow let’s get into boss fights!