Project 1: Space Shooter
Adding the final enemy type
Nastiest of them all
Time to add the last enemy type, at least for now, this one can not only shoot a homing missile it can also teleport.
For the most part this enemy is exactly the same as the basic type. Additionally it can shoot a homing missile at a random interval. The homing missile itself is the same as the missile done for the player.
That is the already existing OnTriggerEnter2D and the OnTriggerExit2D, have additional comparisons for the collisions with the player. The easiest way to distinguish between the player’s and the enemy’s missile is to add a Boolean variable _isEnemyMissile, which has a value true when it is the enemy’s missile and false otherwise.
This can be changed to true with the public method AssingEnemyMissile in the HomingMissile script, and read inside the HomingDetector script with the public method IsEnemyMissile so that the detector also knows which target or targets to follow.
Then all there is to do is to add a new FireMissile method to the enemy script so that the missile can be shot. First it calculates the next time the missile can be shot, this is anywhere between four to eight seconds added to the current time obtained with Time.time method.
The position where the missile is instantiated is defined next as a Vector3 variable called position. Since the original missile prefab was made for the player, the missile has to be rotated 180 degrees for it to move to the right direction relative to the shooting enemy. The last part is to make the instantiated missile the enemy’s missile.
The teleportation on the other hand is handled by the method Teleport. It randomly selects a time between three to seven seconds from the current time as time for the next teleport. After that it selects a random spot inside the game area to be the next destination.
Before teleporting to the new location it checks if the player is too close to the jump location. This is to prevent accidental collisions with the player, although it could be used as a ramming type weapon I didn’t want to use it that way. After all this is the only enemy with the homing missile. To put more distance between the enemy and the player a random value between zero and one is added to the random position.
Lastly it starts a coroutine which does the actual teleportation. First it stops the enemy, then makes it transparent by manipulating the SpriteRenderers alpha-channel. After that it waits for 0.5 seconds before switching location.
Once the teleportation has happened all of the previous steps are done in reverse. That is, first the wait, then the alpha-channel is returned back to one, after which the speed is set to the base speed of 3.5.