Diversifying Enemy Tactics

Pew pew pew!

In the 2D shooter I’m building in Unity I’m adding in new ways for the enemy to shoot. I want some percentage of the enemies to have a rearward sneak attack. If the enemy and the player are directly behind one another, the enemy will fire back a shot. I also want the enemies to look for and shoot at powerups, so that the player has a harder time getting everything that falls from our too-generous powerup spawner.

Let’s add more shoots. Starting with firing backward at the player.

First thing I need to know is the direction to the player. There are several ways, but I went with finding the Vector3.SignedAngle between the player’s position and the enemy’s position. Angles are represented by half circles of +-180 degrees, so if the player is within +-10 degrees of the enemy’s up (green) vector then we can instantiate a laser.

I also need to make a small change in the laser code to toggle its movement direction based on a _fireDirectionUp bool.

Lastly, I’ll set the chance that any enemy has a rearward weapon at 1 in 10, to keep it from becoming overwhelming at later stages. Just an occasional surprise.

Then we do pretty much the same thing for targeting powerups. Only, one small problem: powerups aren’t as easy to identify as the player is. How will the enemy find the object?

As always there are numerous routes. I chose to put the powerups in a public list from the SpawnManager class so that the enemies can look and see if any of the objects on the list are in front of it.

Once I have the list populating, I can get the targeting method done. Once again, I’ll need the System.Linq namespace enabled so I can keep the list clean of destroyed powerups.

Walking thorough: this method is called on update, so the first thing I want to do is make sure we’re not looking for dead powerups before the rest of the looping. Same as with the enemy list, I use Where(e => e != null).ToList() to cull the missing objects.

From there, for each count on the powerUpList we find the direction to it, compare if it fits within the ranges ahead and behind, and shoot some lasers if it happens to be so.

That’s all it takes. In the next article we’ll put together the last of our perks for the player, and then we’ll be ready to tackle the boss encounter.

Unity Developer / Game Developer / Artist / Problem Solver