Adding Enemy Aggression with Distance

Frank Warman
Nerd For Tech
Published in
2 min readMay 28, 2021

--

We created our Kamikaze Enemy that always moves towards our Player. But what if we add some functionality that our regular Enemies could “ram” the Player when they get too close?

That’s what’s going to happen in today’s article!

“Baby come back!”

Inside the Script

All of our “Ramming Logic” will be within the current Enemy script.

First we can create some Global variables to use throughout the script:

  • _rammingDistance = how far away before we trigger the Enemy aggression
  • _spriteRenderer = a reference so we can change the colour of the Enemy, letting the Player know they are in “aggression” mode
  • _rammingSpeed = how fast the Enemy will charge the Player

Nest we’ll initialize our reference to the Sprite Renderer in Start():

Don’t forget to null check!

Then we’ll create the logic for the EnemyAggression() logic:

I’ve set it up so that the Enemy will only attempt to charge the Player if they are above them on-screen (if (transform.position.y > _player.transform.position.y), allowing the Player to escape the aggressive Enemy.

Gizmos are your Friend

When determining the right value to set something, such as distance in our case, it’s very helpful to use Gizmos to visualize the distance in your Scene Window.

By adding OnDrawGizmosSelected() inside your script, you can visualize your values, and tweak them in the Inspector (using [SerializeField] or public variables) to achieve the right distance!

To visualize:

DrawWireSphere appears as a circle in 2D!

With that, we’ve successfully given our Enemies a little more spunk! Now evading enemies isn’t as clear cut as it used to be!

In the next article we’ll be creating another new Enemy… this time giving them the ability to shoot backwards!

--

--

Frank Warman
Nerd For Tech

Audio Engineer turned Unity Game Dev. Will be combining both my skillsets when appropriate, and will be documenting my Unity Dev growth in these Medium Articles