62-Enemy Avoid Shot from Player

In this post, the aggressive enemy will try to avoid the laser shot from the player.

To implement this behavior, the enemy has to know when it is on the path of the player’s laser and move away from that path.

There are two things to detect between the enemy and the laser shooting at it: vertically, the laser should be below the enemy; horizontally, the distance between the laser and the enemy is within a certain range (such that their collider will interact, i.e., |laser.position.x-enemy.position.x|<half of the enemy’s collider size in X direction).

The last bit to consider is which direction the enemy should dodge and by at least half of the enemy’s collider size in X direction:

// if laser is to the left of the enemy’s center
// dodge to the right
// if laser is to the right of the enemy’s center
// dodge to the left

By implementing the above logic in code, the dodging behavior can be realized.

--

--

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
YShu

YShu

Technologist and Unity developer