An Enemy that Fires Backwards

Blake Zoeckler
3 min readJun 11, 2021

--

Objective: create a new enemy type with unique movement, that turns around when behind the player.

We’ll call this new enemy the TripleShotEnemy, since it will shoot three lasers at a time. I used an empty gameobject called Hitbox with it’s own BoxCollider2D in order to better represent the shape of this ship.

Credit to MillionthVector

Time to get started on TripleShotBehavior. First we need to do some basic setup, set the enemy on the right side of the screen, and randomize it’s sinusoidal behavior. We start a firing coroutine, and also make sure there’s exactly three projectile offsets since we’ll need them when this enemy fires. These offsets are Vector3 variables that determine where the lasers should appear when they are fired. Without them, we would have all three lasers fire from the center of the ship, which would look kind of weird.

The act method controls the movement. Movement horizontally is simple and acts very similarly to basic enemies that just move left and wrap around the screen. However, the vertical movement is based on a sin function, which gradually moves up and down the screen. Then, if this enemy is behind the player, we start a coroutine which turns this enemy around.

We turn the enemy around by taking the enemy’s default Z rotation and adding 180. This gives us a new target rotation which we then can linearly interpolate to over some amount of time.

Now the firing of this ship is similar to basic enemies as well, except there’s three lasers and we have to account for the fact that the enemy could be rotating around. We can calculate which direction to shoot the lasers based on how much the enemy has rotated, if at all. We know that we usually want to shoot the lasers left, so 180 degrees is the default for the middle laser. Then we can add or subtract by the shot spread variable to get the other firing angles. Now we can just call the EnemyBehavior.FireProjectile inherited method three times to make three lasers.

Note that the projectile offsets are multiplied by a quaternion. We can apply rotation to any vector by multiplying them like that, which is a handy way to also make sure that the offsets are also rotated around.

With that, we have added yet another unique enemy type to the game! It gets easier and easier each time.

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet