Adding Enemies Avoiding Shots in Unity!

O'Daiyah Harper
3 min readSep 7, 2022

--

Objective: Learn how to add enemies avoiding shots in Unity!

What we want is the have an enemy that will be able to avoid the player’s shots.

First, let’s go into the code to start the functionality!

We need to add a bool that will check if the enemy is a dodge type and check if they can dodge. We will be using that variable later.

We can create a float for the amount of time the enemy will be dodging and the random direction they will go in.

Here, we check if the enemy is a dodge type. If so, we give them a random direction between -3 and 3.

In this method, we use a CircleCast to search for the laser. We then check if the laser is an enemy laser. If it is, then we return and have the code do nothing. If it's not, then we can dodge.

We need to call this DetectLaser() method in the FixedUpdate() method!

Now, we can check if the enemy can dodge. If so, we can call the Dodge method we created!

In the Dodge method, we can check if the dodge time is less than 0. If it is, then the enemy can’t dodge, we can reset the dodge time and have the enemy do nothing else.

If those conditions aren’t met, then the enemy can do the dodge!

Awesome! As we can see, the enemies move aside to dodge the player’s laser! Take note that they don’t always dodge, but it looks great when they do! I hope you guys enjoyed the post for today! Next time, I will add a homing projectile power-up!

--

--