Creating an Enemy Type that Can Avoid the Player Lasers
Another smart enemy
Objective: create a new enemy type that can detect the player’s regular laser and avoid it.
First step is to duplicate the enemy prefab and assign a new enemy ID.
Then I created a new empty game object called Laser_Detection_Area, I added a rigidbody 2d and a circle collider a set it as a trigger. We are gonna use this object to detect the laser close to the enemy.
In the enemy script I created 2 variables. The dodge variable is a bool to activate the movement to dodge the laser and the dodgePath is the variable to indicate the dodge direction.
In the same script I created a coroutine to generate a random value for _dodgePath variable a and set the dodge variable as true, wait 3 seconds and set it as false again. As well I created another function to start this coroutine.
In the update method I added a condition to check if the enemy is and enemy of type dodger (ID == 4) and if the dodge variable is true. Then we only have to use the function translate to move the enemy and avoid the shot.
In the laser detection area script I used the OnTriggerEnter2D function to check if some laser enters to the area and call the function to activate the dodge coroutine.
And that’s all!!! We have a new enemy that can avoid the player lasers.