Day 55: Enemy can dodge?!

Tyler Smallwood
3 min readJun 22, 2021

--

Objective: Allow an enemy a chance to move to the side and not get hit by the player’s laser.

To start off lets create a new script that inherits from the Enemy class.

Next let’s override our CalculateMovement function.

Inside this CalculateMovement we will assign a collider to a Physics2D.OverlapBox. This OverlapBox needs a position, so we gave it the current position of the enemy and offset it down on the why to right before the nose of the enemy ship. Next is the size of the box, we do this by creating a new vector 2 and giving the x axis a 1 and y a 2. We created a rectangle!

To see how this looks we can use OnDrawGizmos. We put Gizmos.DrawCube with the same values as above to get a visual.

Back in our CalculateMovement function, we check to see if the collider is not equal to null and the enemy is not destroyed. If it’s null or destroyed move on. If it is not null or destroyed move on and check to see what is in the box. If it is equal to the Laser move to the PickDirection function.

In the PickDirection function, we pick a number between 1 and 5. If it’s 1 move right by 2, if it’s 2 move left by 2. If it is any of the other numbers, don’t move.

This is a way we can get the enemy to have a chance at dodge the players lasers.

Thank you for reading! Have a great day!

--

--

Tyler Smallwood
Tyler Smallwood

Written by Tyler Smallwood

I am passonate on learning to program and use Unity to become a skillful Unity Developer

No responses yet