Creating an Enemy That Dodges Lasers

Blake Zoeckler
3 min readJun 13, 2021

--

Objective: create an enemy that dodges the player’s projectiles

Credits to MillionthVector yet again.

DodgingBehavior is the new class we create for this enemy. This enemy will start on the right side of the screen, and GetNewDestination will find a random point on the screen to move to.

DodgingBehavior.Start

Here’s the Act method that is called every frame. As usual, we get a “progress” time value between 0 and 1 in order to control the exact position between the starting and ending points of the movement. In this case, we apply a mathematical function to it in order to get more “dodgy” movement. We also check for incoming lasers every frame.

DodgingBehavior.Act

Here’s a graphical representation of the function used for the dodgy movement. The horizontal axis represents time, and the vertical axis is position. This causes the enemy to move quickly when it’s just beginning to move, and then it slowly comes to a stop as it gets closer to the destination.

CheckForLasers will look through the scene for every gameobject that is tagged as a projectile. It will detect any projectile that the player shoots. Then, if that projectile is nearby the enemy, and if its current position is “invalid” because it will be hit by that projectile, then it will dodge by getting a new destination and moving there.

DodgingBehavior.CheckForLasers

GetNewDestination works by finding a random point inside the _movableArea bounds variable. This variable controls what locations this dodgy enemy can move to, and is set up in the inspector. If the new location is still invalid because the same laser will hit the enemy there, then we just continue looping and finding another random point until we find one that is valid. After finding a valid location, we setup the other variables to prepare the Act method to actually move to that new destination.

DodgingBehavior.GetNewDestination
_movableArea in the Unity inspector

Finally, IsPositionInvalid compares a certain position against an incoming laser. Any position is valid if the given laser is null (which is what happens when we setup this enemy in Start). If we do have a laser we are trying to avoid, then the enemy will move a copy of their collider box to the location that we want to test, and then see if the laser will hit the collider if it continued moving to the right.

DodgingBehavior.IsPositionInvalid

All done. Applying this new behavior to the enemy gameobject, along with all the other necessary components, creates a frustrating enemy that is very difficult to hit!

Next time, we’ll work on giving this enemy a way to attack a player, but also make it more vulnerable to attack as well.

--

--

Blake Zoeckler
Blake Zoeckler

Written by Blake Zoeckler

I’m a passionate and talented software engineer seeking an opportunity in game development.

No responses yet