Adding in an Avoid Shot Feature for our Enemy in Unity 2D!

Chris Hilton
2 min readSep 14, 2021

Objective: To give our enemy a detection mechanism that teleports them out of the way of the players lasers!

Now that we have setup some new movement for our teleport enemy, we are going to add in a new feature that uses raycasting to detect when a players laser is in front of it and then it will teleport out of harms way to a new position on the screen within set boundaries. There is also going to cooldown for this feature to make sure that we are actually able to destroy it! Let’s get into it…

Let’s Start With Some Code

We only need to work within the “TeleportEnemyBehaviour” script for this one so let’s open it up:

Let’s create some variables that are going to cover the ray detection length; a trigger bool switch for the cooldown coroutine; an offset for our ray detection so it isn’t stuck in the middle of the enemy sprite and we are going to cache the WaitForSeconds class as we are going to use this a few times.

Also don’t forget to call this within Update() as we want this raycast to be running every frame. Next we will look at setting up the AvoidShot() method:

This code is almost identical to the one we used to implement the aggressive enemy feature for our original enemy except that instead of looking for the ‘player’, we are going to detect the ‘Lasertag.
Jump over to the other article for a more detailed explanation:
https://christopherhilton88.medium.com/making-an-aggressive-enemy-in-our-2d-galaxy-shooter-in-unity-b39a9766bd40

Finally, this is our timed coroutine that simply triggers our bool switch to be enabled and then we wait 3 seconds and then it becomes disabled.

--

--