An Aggressive Enemy that Rams the Player
Objective: Create a new kind of enemy. If this enemy is close to the player, the enemy will try and “ram” them.
Using what we’ve learned so far, we can create the behavior for this new “rammer” enemy by using a state machine, just like we did for the smart enemy. We can just reuse the same basic structure.
Similarly to the SmartEnemyBehavior, this new enemy will go through a loop of 4 different states:
- Moving: The enemy appears on the right side, with its default rotation and scale settings. It then moves to the left, just like a basic enemy. When this enemy comes within a certain distance of the player, it switches to the Preparing state.
2. Preparing: The enemy will no longer move. Instead, we determine the direction to the player and rotate towards that point over a short period of time, by using linear interpolation. When that period of time has elapsed, switch to Ramming state.
3. Ramming: The enemy will rapidly accelerate in the chosen direction in an attempt to collide with the player. We also increase the size of the enemy’s thruster graphic and play a rocket sound. When the enemy has flown far enough off screen, switch to Reappear state.
4. Reappear: It wouldn’t make much sense if the enemy rocketed off the screen and then immediately appeared on the right. Instead, the enemy will just wait off-screen for a short duration, then switch back to Moving state.
Here’s the finished RammingEnemy prefab and it’s new behavior script. It doesn’t shoot projectiles, so it doesn’t need a projectile game object or audio clip.
That’s all there is to it. As always, the Enemy script will call the Act method of this new behavior automatically and take care of the rest. All the component setup we’ve done before makes adding new enemy types really easy!
In the future, we may add some more polish to this. I’d like to have a red, flashing warning light that warns the player what the rammer is about to do. It’d also be nice to have some particle affects while the rammer enemy zooms off screen.