Adding a new type of enemy movement to my space shooter

Now that the boss battle is out of the way, I want to add some more features to the enemies. I added the randomly shielded enemies, but I want more diversity of enemy types. I want to make one that flies in the direction of the player and is faster than normal enemies.

I already have the bones of a switch-statement in the enemy script to handle adding more types of enemies. I just made a new case and added some logic that I’ll use later. It sets a boolean ‘isAngleEnemy’ to true and also gets a reference to the current player location. It then creates a new Vector3 using the player position values, but adds a random value (between -2 and 2) to the x-position so that it moves in the general direction of the player. The y-value becomes 10 units below the player so the enemy is aimed at a point beyond the player and can move off-screen.

Enemy.cs

To implement this, I just added an if-statement to the movement method to check if it’s an angled enemy. If so, it moves toward that vector at double the usual speed. But I also want it to rotate towards that point, so I need to play with the rotation value. I subtracted the x and y-values of the enemy from the target position to get the lengths of the opposite and adjacent sides of a right triangle. Then I used the arc-tangent function (Mathf.ATan()) to get the angle, in radians, from the enemy to the target. Multiply it by the built-in Rad2Deg constant, and it gives you the angle in degrees so it can be used to set the rotation directly.

Enemy.cs

I have all enemies spawning as angled to demonstrate here. Normally, they would only have a 10% chance to spawn like this.