Phase II: Smart Enemy

Brian Branch
3 min readJun 18, 2021

--

This article is about how I set up a new, smarter enemy to challenge the player.

Objective: Create a new enemy that detects when the player is behind them and fires a shot at them.

As I discussed in my previous article on Refactoring my Code, adding new enemies with additional functionality is much easier now.

First, I created a SmartEnemy script and set it to inherit from the BaseEnemy class. This allows it to have all of the functionality and a basic normal enemy.

I then added a private float _revFireTime = 0.0f; to determine if enough time has passed for the enemy to fire backward.

The challenge was in detecting the player behind the enemy. After looking into how to do this and getting some advice from Austin Mackrell, I settled on using a Raycast to check when the player is behind the enemy. So I cast a 2D Raycast going up from the enemy and also used Debug.DrawRay to visualize the ray in the scene view.

The parameters in the raycast do the following:

  • transform.position - This is the starting position of the ray. Since I want the ray to start from the enemy, I use the enemy’s transform.position as the starting point.
  • Vector3.up - This is the direction the ray will travel from the enemy. Since behind the enemy will be up on the screen, we use Vector3.up.
  • 5.0f - This is the distance from the enemy the ray will travel. I set it at 5, giving a nice range to detect the player without being too much.

You can see the ray from the scene view in the screenshot below.

Next is the code to see if the Player is hit by the Raycast and fire the laser backward.

First, I check to see if the collider hit by the Raycast is null. Then to double-check, I Debug.Log the tag of the collider that has been hit.

Then I assign a random number to _fireDelay (inherited from BaseEnemy) to add some variance in how often the enemy can fire backward at the player.

Next, I check if the collider that was shit has the Player tag and if the current Time.time is greater than the _revFireTime.

If all of the above is true, I do the following:

  • Set the _revFireTime = Time.time + _firedelay.
  • Play the _laserAudio AudioSource (inherited from BaseEnemy.
  • Then I instantiate the _enemyLaser (from BaseEnemy) at the enemy transform.position, and I use Quarternion.Euler to keep the same x and y rotation but spin it 180 degrees on the z-axis so that it will travel up when instantiated.

You can see below that the enemy will fire as soon as the player passes behind them.

That is how I implemented an enemy that can fire towards the player even when they have passed by.

I hope you enjoyed this article, and until next time I wish you well on your coding journey.

--

--