In this article, I will discuss the implementation of the dodge mechanic for enemies.
The dodge mechanic is quite simple, the enemy detects an inbound attack and moves out of the way to avoid the attack.
The ability is reusable with a set cool-down time. When the enemy is spawned they have a 50/50 chance of gaining the ability. I have ensured that the enemies cannot have the ability to shoot backward and dodge.
The first step of the function is to detect the inbound attack. This is done via a circle cast. I have set up a new layer called “laser” and assigned this to a layer mask. This layer mask ensures the circle cast is triggered only for the player's attacks.
The “scan for attack” function initiates the circle cast and passes in the point of impact of the laser when it collides with the cast. This is passed as a vector-3 to the “dodge” coroutine.
The dodge routine compares the “hit point” to the enemy's current position. Using the calculation the enemy will add a positive or negative value (to move left or right) to its x-direction and moves backward to move away from the laser.
I added a new enemy which has a low spawn rate but can recharge its dodge ability quickly. Let's set the enemy and dodge ability in action.
That’s all for now.