Phase II: Enemy Destroy Pickups

Brian Branch
3 min readJun 20, 2021

--

Objective: The objective today is pretty straightforward. We want a new enemy type that will detect powerups in front of them and will fire at and destroy them to keep the player from getting them.

This objective builds very nicely with some of the previous ones since it involves detecting an object in front of the enemy and performing an action when it is detected.

First, I’m going to create a new enemy, and in its script, it will inherit from the BaseEnemy class. I’m going to name it the EnemyXPowerup and will use the sprite below.

EnemyXPowerup, an enemy that can destroy powerups.

The script for the new enemy will be pretty easy since most of its behaviour will be inherited. I will add a private bool _canShoot and initially set it to true.

This is because I only want the enemy to be able to destroy a single powerup. I may decide to change this later, but that is a limit I am setting for now.

Next, I use a raycast to check if anything has been hit, and I also perform a Debug.Raycast to visualize the ray in the scene view.

Then after I check to make sure the collider is not null, I check to see if the conditions are met before having the enemy fire a laser.

Let’s go over my conditions since I have three that have to be met.

  • hit.collider.tag == “Powerup”: All of my powerups are tagged that way, so that is the first check. As long as that’s true, we go on to the next one.
  • _canShoot == true: This obviously checks if the enemy is even able to shoot at a powerup or if it has been disabled.
  • hit.collider.name != “Negative_Powerup”: Because I have a negative powerup that occasionally spawns, I don’t want the enemy destroying that. It shares the Powerup tag, so I can’t check using its tag, so instead, I use its name.

Once all of that is true, I play the sound for the laser, instantiate the laser, then change the _canShoot bool to false so that the enemy cannot shoot at a powerup again.

Next, I had to set up the Powerups so they can be destroyed. First, I created two variables, one for a GameObject and the other for an AudioClip.

Since I already have a collider on the Powerups with an OnTriggerEnter2D() event in their script, I had to add what to do if the enemy laser hits them.

If the EnemyLaser is hit, I destroy the laser, play the explosion AudioClip, instantiate the explosion GameObject, then destroy the powerup. You can see how this looks below.

That’s how I created an enemy that could keep the player from getting a valuable powerup.

I hope you found this interesting and maybe at least a bit helpful. So until next time, I wish you all the best on your coding journey.

--

--