Spiteful Enemies

Ryan Sweigart
2 min readMay 7, 2021

Let’s give our enemies the ability to deal a low blow to the player: By destroying precious power-ups!

It’s easy enough to tell our enemy lasers to destroy anything tagged “Power Up.” But our enemies normally have countdown timers so they don’t shoot constantly. How do we allow them to take an extra shot when they detect a power-up, but not spam the screen with a hail of lasers? Let’s look at the solution:

Every frame, if the enemy has the ability to detect power-ups, the DetectPowerup method is called. If the enemy has NOT taken a shot at a power-up recently, it will “draw” an invisible box at the position of its sensor (an empty game object assigned in the inspector). This box is defined as tall but narrow to sense targets near the enemy’s y-position on-screen (in the same “column,” if you will). We use a LayerMask to detect only power-ups. If a power-up is in the box, we set _hasTakenPowerupShot to true and fire a projectile with the FireProjectile method.

During the next Update method, the enemy will not look for a power-up since _hasTakenPowerupShot is true. When the FireProjectile method was called, the shot timer was reset to 0. This stops the enemy from taking another cheap shot. Once the shot timer expires, _hasTakenPowerupShot is set to false, and the process can begin anew.

This will show those cheeky players!

DENIED!

--

--