Giving the Dodging Enemy a Weapon… and a Weakness
Objective: give the new dodging enemy a beam weapon, and make it vulnerable while firing this weapon.
We create this beam as a child object of the new enemy. It’s actually just the same laser sprite that we’ve been using, but extremely stretched out lengthwise.
This new beam weapon has a new Beam script, so it counts as a projectile, but doesn’t move. It has it’s own collider and rigidbody, and if the player collides with it while it’s activated, then the player will be damaged.
Now we change the structure of the DodgingBehavior to that of a state machine, similar to other enemies. DoMove now causes the enemy to move and dodge, like how Act used to.
In addition, we will switch to the charging state when enough time has elapsed. In the meantime, the enemy will slowly rotate toward the player’s position to try to line up its beam weapon. We achieve this rotation by getting the direction to the player, and comparing that to the current facing direction of the enemy. This gets a degree measure that we want to rotate, and we can just cap it by our rotation speed so the enemy doesn’t immediately snap to the correct direction.
When charging, we turn on the charging sprite. The charging sprite is a small ball that grows larger over time as the beam weapon charges. When it’s finished charging, we switch to the firing state.
A coroutine also runs that causes the a warning line to flash on and off. This sprite is just a very stretched red rectangle. It’s important to have this, because this enemy could be hiding in the back of other enemies and be hard to notice where it’s aiming. This flashing red line gives the player a brief warning so they know how to dodge the incoming beam.
When firing, we turn off the charging sprite and warning line, and active that beam weapon object, while playing a sound. The beam weapon will automatically collide with the player while it is active.
Finally, switching back to the moving state will turn off the beam weapon, and get a new destination to move to.
All done. Here’s the brief example of the new behavior of the enemy. It still dodges laser shots by default, but after staying in place for a short time, it will try firing a beam. That’s the chance to retaliate and defeat the enemy while it is vulnerable! It’s always wonderful to add a clever mechanic like this to a game.