Adding a smart enemy

The next requirement is to make the enemy shoot from its tail if the player is behind it. However, not all enemies are smart enemies so we will randomize this again and enable it based on weights. I added these attributes on the enemy:

private bool _isSmartEnemy = false;
private int _smartEnemyWeight = 20;

Then on the Start() method of the Enemy, I enable this behavior based on weights:

weightRequired = Random.Range(0, 101);
Debug.Log("Random Weight Required: " + weightRequired);
if (_smartEnemyWeight >= weightRequired)
_isSmartEnemy = true;
_isSmartEnemy = false;

The enemy needs to be able to detect the Player so we need a rear collider for the Player. I also added a tag PlayerPresenceRear so that if it’s triggered we can determine which collider got hit.

Then, on OnTriggerEnter2D of the Enemy, we can check if the that collision is detected, the enemy is smart and if the player can fire:

if (other.CompareTag("PlayerPresenceRear") && _isSmartEnemy)
if (Time.time > _canFire)
_fireRate = Random.Range(3f, 7f);
_canFire = Time.time + _fireRate;
Instantiate(_laserRearPrefab, new Vector3(transform.position.x, transform.position.y, transform.position.z), Quaternion.identity);

I added the _laserRearPrefab to the Enemy and it will be instantiated behind the enemy:

After implementing these changes, the demonstration below shows some enemies shoot from behind if they are smart.

I love game design and development.