Making the enemy dodge player’s attack in Unity

The exercise here demonstrates making the enemy detect the player’s laser and move it sideways to save itself from getting destroyed.

The plan is as followed.

  • Detect the laser presence at a certain distance from the enemy prefab.
  • If laser detected, instruct the enemy to move either left or right at a certain value by checking where the laser’s position is.

To detect the presence, the first requirement is to see which object should check the presence. If the enemy prefab does, by the time the presence is detected, it should be destroyed.

So, there must be another object that only specializes in detecting the laser presence only and has nothing else to interact with.

  • Create an empty object on the enemy prefab that should dodge the laser attacks.
  • Make it generously long enough which makes detection neither too early nor too late.
  • Add a box collider with IsTrigger( ) ticked and a rigidbody with a kinematic body type.

Here is a little caveat. If the rigidbody is not made so, the empty game object will inherit the parent’s behavior which eventually will be damaging the player without any attack in between.

  • Apply the changes to the enemy prefab by overriding it.
  • Create a new script on this empty object and add a trigger check method.


  • Now, the collision object shall be checked for its x position to determine the direction in which the enemy shall move instantly.
  • Also, this object should call a method from the enemy script and the method should change the transform.position.x value to something predetermined.
  • The dodge method is expecting a float value that it adds in the current x position of the enemy prefab.
  • The collision check method is checking if the x position of itself is less than the position of the laser object, it should move left so that the laser will pass by and, in the other case where the current position of itself is more than the position of the laser object, it should move right.

That should work.

Here is the final result :)

Thank you very much

Work in Progress.