Nerd For Tech
Published in

Nerd For Tech

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.

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store