Player Advantage? Enemies Destroy The Power-Ups! (Part 2)
Shooting at Powerups in front of them is good, but what if they could destroy any powerup, anywhere? Following on from Part 1, we’ll make the enemies able to shoot any Powerup at a lower Y position than them.
Today’s Objective: Make the enemies shoot at and destroy any power-ups that are in front of them, stopping the player from collecting them. The Powerups do not need to be directly in front of them with this version.
First I add a Line Renderer component to my Enemy prefab:
Then, I make some new variables in my Spawn Manager script:
- A public static List of Transforms for all currently existing Items.
- A public static Boolean variable to return if any Items currently exist.
- A public static Int variable to return the Item count.
- And a public static function to update the List.
The function is called when an Item is spawned, adding it to the list, and when an Item is destroyed, removing it.
The Laser-Targetting Process in the Enemy Gun script:
- Get a list of all Powerups in the scene.
- Remove any Powerups behind the Enemy (plus a buffer distance) from the list.
- Find the closest Powerup to the Enemy in that list, and set as the target.
- Optional: I have 2 ship guns, so I will use distance to choose which gun to shoot from.
- Activate the Line Renderer and target the targeted Powerup for the duration of the shot.
- Destroy the Powerup and deactivate the Line Renderer.
Get and sort the list of Powerups:
Get the closest Powerup:
Determine which gun, maintain the Line Renderer, and Destroy the Powerup:
Inside the coroutine, add the following:
Also make a public function to start the coroutine:
Lastly, we need to determine when these functions will be called:
I want it to happen every time the enemy exits the bottom of the screen and repositions to the top. So I will go to my code that checks if it has reached the bottom of the screen:
And the result:
I think it turned out great, and maybe with a low chance of activating, would be a good additional difficulty for players. I think I’ll set it to a 5% or 10% chance an enemy will target a powerup every time they reposition to the top of the screen.