Smart Enemies Fire from Behind

This tutorial covers how to give enemies the ability to fire behind themselves when the player is behind them. To start go to the Laser script. It needs to be edited to allow for the enemy to fire up on the screen. Add a new global variable to keep track of the direction the laser is to fire.

[SerializeField] private int _laserDirection = 0;

Next, change the Update function to use the laserDirection variable instead of the enemy variable.

void Update()
{
if (_laserDirection == 0)
{
MoveUp();
}
else
{
MoveDown();
}
}

The next change to make in the Laser script is to update the AssignEnemyLaser function so that it takes a variable and assigns it to the laser direction variable. Remember to update the call to this function in the Enemy script FireLaser function.

public void AssignEnemyLaser(int direction)
{
_isEnemyLaser = true;
_laserDirection = direction;
}

Now move over to the Enemy script. The first thing to do here is add three variables. One to track how often the enemy fires behind them and the others are for the laser going up or down.

private float _canFireBehind = -1f;
private int _laserDown = 1;
private int _laserUp = 0;

Next, update the FireLaser function. Add code to move the laser instantiate position up when it is fired upward. Add an input variable for the direction and pass this to the Laser AssignEnemyLaser function.

void FireLaser(int direction)
{
_fireRate = Random.Range(3f, 7f);
_canFire = Time.time + _fireRate;
Vector3 laserPosition = transform.position;
if (direction == _laserUp)
{
laserPosition += new Vector3(0f, 2f, 0f);
}
GameObject enemyLaser =
Instantiate(_laserPrefab, laserPosition, Quaternion.identity);
Laser[] lasers = enemyLaser.GetComponentsInChildren<Laser>();
for (int i = 0; i < lasers.Length; i++)
{
lasers[i].AssignEnemyLaser(direction);
}
}

Now add the code to check for the player behind the enemy. How the enemy detects when the player is behind them is similar to how the enemy detects if a powerup is in front of them from this tutorial. Now you are checking for the Player instead of a powerup.

private void CheckForPlayerBehind()
{
Collider2D hitCollider =
Physics2D.OverlapBox(gameObject.transform.position +
new Vector3(0f, 5f, 0f), new Vector3(0.18f, 4f, 0f), 0f);
if (hitCollider != null)
{
if (hitCollider.tag == "Player")
{
FireLaser(_laserUp);
_canFireBehind = Time.time + _fireRate;
}
}
}

That is all you need to make the enemies a little smarter.

-Chris