Aggressive Enemy Type
Now let’s create a new enemy type that will detect when our player is within range and change direction to try and ram the player.
Here’s what it will look like when we’re done:
There are a couple of ways we can have the Enemy target the Player. One simple solution would be to check the distance between the Enemy and the player during the Update method. Something like this on the Enemy script:
One disadvantage of this is that when the screen is full of enemies, the system will be burdened with checking the distance on each Enemy on every frame, and that could slow things down.
The approach we’re going to use is to add a new child Gameobject to the Enemy that has it’s own trigger and use that trigger as our “radar” to let us know when the player is inside our range.
So, let’s add a new game object to Enemy and call it Radar. Give Radar a Circle Collider 2d, and a Rigidbody 2D. Let’s create a Script for Radar.
We need a variable to indicate we are in chase mode, so let’s create a method on the Enemy script to set that variable:
Now we can make some additions to Enemy.Calculatemovement() that change our Enemy direction when the Enemy is in chase mode:
So now we just need to update our Radar script to call ChasePlayer when the Radar trigger is activated. Just for fun, we’ll set it so that if the Enemy has already passed the Player, the Player is safe from being pursued. And, when the player exits the Radar range, the Enemy will stop pursuing. Here’s the script: