Creating an enemy that dodges in Unity

Daniel Kirwan
3 min readApr 29, 2021

--

Today we’re going to take a look at making one of our enemy types dodge our incoming shots.

I have already chosen my enemy type to try the dodge code on. But let’s think about what we need to do before looking at the code.

We need the enemy to be able to detect one of our lasers and then move up or down the screen to avoid the laser. To do this we need to use a raycast from our enemy. A raycast is essentially a ray that gets sent out from a position in the world in a certain direction.

For the space shooter we will be using 2D raycasts. So first off we need to create the raycast.

We need to use a 2D raycast as our game is in 2D and then I am using the CircleCast method. I am giving the parameters of (enemy position, the radius, the direction I want the ray to go, and the layermask).

To visualise the raycast in the scene view in Unity you can use the gizmos method provided by Unity.

This will draw a wiresphere around the position you enter. Make sure to enter the same radius as the circle cast. Now, in Unity you need to make sure you have the gizmos option selected in the scene view.

You can see both the wiresphere and where you can turn on and off the gizmos option.

It is now time to move the enemy if it detects anything on the Layer called “Laser”. For this part you will need to create a new layer in Unity. Click on your game object and look in the inspector, in the top right you will see an option for Layer. You then need to add a new layer with the same name as you have put into the circlecast. For me that will be Laser. Now select the game object again and add the game object. I am adding the Laser layer to my Laser prefab game object.

This means that the raycast will ignore everything else on all other layers and will only detect objects on the Laser layer.

Now comes the movement.

First make sure to null check your raycast. I am making sure that the object it has collided with has a collider. I am then checking to make sure that the object has a tag of “Laser”.

I am then doing a series of checks to the position of the collision(hit point) and the enemy objects position.

If the enemy position is above the hit point then the enemy will move up and if the enemy position is below the hit point then the enemy will move down. I am then setting the bool for if the enemy can dodge to false. Otherwise they will always dodge our shots.

And that’s it for this article.

--

--

Daniel Kirwan
Daniel Kirwan

No responses yet