Enemy Destroying Powerups

Christian Carter
3 min readAug 18, 2021

This tutorial will cover enabling the enemy to fire at powerups and destroy them. To start you need to give all of the powerups a tag named “Powerup”. This will allow the enemy lasers to recognize the powerups and destroy them. To set up a new tag select a powerup then in the Inspector in the Tag drop down select Add Tag. That will take you to Tags and Layers. Click the plus icon to create a new tag. Give it the name Powerup. Now go through each of the powerups and assign them the new tag.

Next, go to the Powerup script. Create a new function called PowerupDestroy. Destroy the gameObject in it. This will be used to destroy the powerup from the Laser script.

public void PowerupDestroy()
{
Destroy(this.gameObject);
}

Now go to the Laser script. In the OnTriggerEnter2D function add another if statement to check if the the other collider has a tag of powerup. Get the Powerup component and call the PowerupDestroy function and destroy the laser gameObject.

if (other.tag == "Powerup" && _isEnemyLaser == true)
{
Powerup powerup = other.GetComponent<Powerup>();
if (powerup != null)
{
powerup.PowerupDestroy();
Destroy(this.gameObject);
}
}

The last step is to check if a powerup is in front of the enemy. First add a variable to limit how often the enemy can fire at a powerup just like the enemy is limited in how often it can fire.

private float _canFireAtPowerup = -1f;

Next, in the Update function add an if statement to check if it can fire at a powerup. If it can call the function CheckForPowerups. You will make this function next.

if (Time.time > _canFireAtPowerup && _isAlive == true)
{
CheckForPowerups();
}

Last, create the CheckForPowerups function. The first part of the function uses Physics2D.OverlapBox. That function will check in a box for a colliders it touches. It will return a collider it hits. The three variables you pass to it are the center of the box which you want out in front of the enemy and the next is a vector to one of the corners of the box, the last is the angle which can be set to 0. You then check if a collider is returned and check if it has a Powerup tag. If it does fire the laser and update when it can next fire at a powerup.

private void CheckForPowerups()
{
Collider2D hitCollider =
Physics2D.OverlapBox(gameObject.transform.position +
new Vector3(0f, -5f), new Vector3(0.18f, 4f), 0f);
if (hitCollider != null)
{
if (hitCollider.tag == "Powerup")
{
FireLaser();
_canFireAtPowerup = Time.time + _fireRate;
}
}
}

That will allow the enemies to fire at the Powerups and destroy them!

-Chris

--

--