Giving the enemy a dodging chance.

Chance Cornell
2 min readAug 21, 2021

In this article, we create an enemy type that can dodge shots from the player.

To start we need to duplicate an enemy prefab and place it in the hierarchy. We will rename it as ‘Enemy_Dodge’. We will create an empty game object on it and call it ‘LaserDetector’. We will add a ‘Rigidbody 2D’ component as well as a ‘Polygon Collider 2D’ that is a trigger. Edit the collider of the polygon collider to look like a cone. This cone will act as the eyes of the enemy and allow them to see lasers coming at them.

We’re going to create a new script called ‘EnemyDetector’ and attach it to the ‘LaserDetector’ game object.

In the ‘EnemyDetector’ script we’re going to create two events based on when the laser enters the trigger area and when it leaves the trigger area.

In our ‘Enemy’ script, we will add some variables for the dodge mechanic to work.

We’re going to create two new functions. ‘DodgeMovement’ will have the enemy move down the screen just like a normal enemy, however, if a laser is detected, it will move to the left or right to avoid it.

‘LaserFound’ will just return the true or false status of the ‘_laserDetected’ bool to the ‘EnemyDetector’ script.

The final thing we need to do is call our ‘DodgeMovement’ function in Update.

--

--