Making Enemy avoid laser shooting at it
Day 49- Making 2D Space Shooter Game
Objective: Make enemy detect when the laser is coming at it and move left or right to avoid getting hit.
We are going to add this behavior to enemy no.5 which rotates and shoots at player when behind so if you don’t know how then check out my other article or if you want to add this behavior in new enemy then create all of its default behavior first.
Now create a empty gameobject and add a polygon collider as its collider and edit it to look like this.
Then create a new script and move all of its behavior inside this script leaving only the OnTrigger function of the enemy to show destroy behavior.
Now create a OnTrigger in the new script to detect the laser when it touches the created polygon collider and sets the avoid bool to true. Here, rand variable will choose which direction to move towards and coroutine to stop moving right or left after some time.
Set your avoid motion to false after the amount of time you want your enemy to move right or left.
Finally add this condition in your Update function to detect if the avoid bool is true; if true then move left or right depending on the random value and if the bool is false then move down by default.