2D Certification: Enemy Avoid Shot

2D Certification: Enemy Avoid Shot

Christopher West
2 min readSep 12, 2022

In the last article, I added a powerup collect feature. Today, I’m going to be continuing the second, and final, phase of the GameDevHQ 2D Game Development Certification track. In this article, I’ll be adding an enemy type that can avoid player fire! The requirement reads as follows:

Tasks:

  • Create an enemy type that can avoid the player’s weapon * When you fire a shot, the enemy should detect a shot in range and try to avoid it.

For this requirement I decided that I would add the new behavior into it’s own script to be added to the new enemy prefab that I would create. This seemed to work out well with the FireBehavior script, so I decided to use the same strategy. I created a new script called EnemyDodgeLaserBehavior. Once I created the new script I knew I was going to have to detect lasers in a vicinity from the enemy. After a bit of searching I decided that the physics classes in Unity had what I needed to detect other game objects within a radius from a point. The Physics2D class has a method called OverlapCircleAll that returns all game objects within a given range from a specified point. Using this method I could retrieve all of the objects within a range and then filter out everything that wasn’t a player laser.

Once I had a list of the lasers within range of the enemy I could calculate the distance between each laser and the enemy to find the closest laser and then change the movement of the enemy to be away from the closest laser. I then performed these checks in the Update function of the new script.

With the script done I attached to a new enemy prefab and placed the new prefab into a test wave I had setup for testing new enemy types. After a little tweaking of some numbers and a speed boost when dodging I had an enemy type that could dodge player lasers!

Next Time!

In this article, I added an enemy type that can avoid player fire. Next time, I'll be adding a homing projectile! If you enjoyed this article, or want to come along with me as I progress on my journey, follow me at gamedevchris.medium.com.

--

--

Christopher West
Christopher West

Written by Christopher West

Unity Game Developer, Software Engineer, Gamer, Musician, and Father. Christopher is a creative that enjoys a challenge and loves coding.

No responses yet