Enemy Avoid Shot

Richard Morgan
2 min readNov 17, 2021

--

Let’s have an enemy type that can avoid lasers fired by the player.

What we’re going to do is create a new enemy prefab and on that prefab we’re going to add a circle collider that detects the player lasers. When those lasers are detected, we’ll check the x position and tell our enemy to move left or right.

So, first let’s copy our Enemy prefab and rename it and add a new Sprite if we want the ship to have a different look. Now we can add an empty game object and on that new game object let’s put a Rigidbody, a Box Collider 2D, and a new script:

Ok, we can turn that into a new prefab and we’re done with the GameObject.

Now let’s update our scripts. We’ll need a new serialized game object in the SpawnManager:

And now we can have it randomly spawned:

Ok, that’s it for the SpawnManager.

Now for the Enemy additions. Our dodging will need a bool to determine if we are in dodge mode, and we’re also going to need a variable to hold the position.x of the incoming laser. Based on the position of the laser, we’ll update our position to move either left or right (at twice the normal speed):

Let’s set these variables in a method we can call from the collider:

All that’s left to do is make the call from the game object with the new collider:

And that’s it.

--

--