Making an Aggressive Enemy in our 2D Galaxy Shooter in Unity!

Objective: If an enemy gets too close to the player, they are going to try to “ram” them with increased speed!

We are going to add this feature to our original enemy type to spice them up a little bit. Luckily for us we some existing enemy raycasting code that we can try to tweak and make our lives a bit easier. Let’s get into it!

Within the “Enemy” Script

We only need to work within the “Enemy” scri pt for this one, so let’s open it up and get started:

Firstly let’s create our variables that we are going to be using; a minimum enemy speed so we can set our speed back to normal after the ram; a ram speed which is double the normal speed; the ram ray distance will be for our raycast which is constantly going to looking for the Player; a trigger bool switch to check if the ram coroutine is playing and we will also be using our existing Vector3 for the raycast.

Then we are going to call our RayCastRamPlayer() method:

Firstly I have used the Debug.DrawRay() to help with building the feature and debugging issues. This can be commented out/deleted once the feature works. Basically it is going to mock the RayCastHit2D in the form of a straight yellow line so I can check distance and player hits etc…

Next we are going to cast our Physics2D.Raycast and store the results in a RayCastHit2D variable. We are going to shoot the raycast from the enemy (with a small offset, so it doesn’t get stuck detecting the middle of the enemy sprite), in the opposite direction to transform.up(down) and at a distance of 4 units.

Next we are going to complete an If check to see if we have hit a collider. This is our null check before moving into the subsection.

Now let’s check to see if that collider’s tag name is equal to “Player” and if it is, we are going to complete our next If check which is to see if the coroutine _ramPlayerCoroutine is already running as this feature has a 5 second cooldown. We don’t want the enemy to be able to constantly ram the player over and over every second.

Then we are also going to call our EnemyRam() coroutine which is going to handle speed changes over time:

We are going to cache this WaitForSeconds variable as it is going to be called a lot when we have multiple enemies on the screen.

Then we are going to set the _ramSpeed to 10 as previously mentioned, wait 0.5 seconds and set it back to 5.

This is our existing modular coroutine that is called when the EnemyRam() coroutine starts. At the same time it starts this cooldown timer.

Finally, we have added an If check in the EnemyFire() method as we don’t want the enemy to be able to fire their lasers as well as ram at the same time:




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store