Dodging Time!- Game Dev Series 50

Objective: Make enemies can dodge the upcoming laser.

When a visible laser is coming, dodging it should be a reasonable behavior.

In this article, we will create a new behavior for our enemies could dodge the upcoming laser.
With this behavior, it will be 2 parts.

  • Laser detecting gameobject
  • Movement behavior.

Create new detecting gameobject

As what we did in Destroying Powerups article, we can create a new gameobject as a child of Enemy and make it as a detector.

The collider of this gameobject is different. We use Polygon Collider 2D to create a triangle to increase the detecting range.

Then we can edit the Enemy_LaserDetector script.

It would be simple with that script. We just need to detect any collided laser prefab with OnTriggerEnter2D.
However, since we are going to change the movement method, we also need to create an OnTriggerExit2D to recover the movement method.

We use a bool as a switch to change the movement in Enemy, which is what we are going to adjust next.

Movement method

First, let’s create a bool as the switch of movement. Then we can create the public that would be called from laser detector script.

Now we have a functional bool, time to dodge the laser.

We create a integer variable first to randomize the direction. Then we can use this random integer in Update().

Now our enemies would dodge our laser with a sudden move.

Quick fix

Since we use the same tag of laser no matter it was shooting from Player or Enemy, there would be quite normal with the enemy sudden dodging its own laser.
To fix this, we need to make a little change in Laser script.

Create a new tag and attach it when the Laser is shot from Enemy.

With that, enemies should no longer dodging their own laser.



A passionate gamer whose goal is to work in video game development.

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
S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.