Giving the Enemy Lasers!
So far our game consists of our Player dodging our Enemies as they fall to the bottom of the screen, while hopefully being able to shoot and destroy them to add to their score.
But now lets add some difficulty to our game and let our Enemy ships fight back!
Creating the Enemy Laser
The first thing we’ll do is create a Laser for the Enemy that has a different appearance from our Player’s Laser.
We’ll do this by creating an Empty Object and using our Laser Prefab, scaling, duplicating it, then fitting it to our Enemy:
Next we’ll remove the Laser scripts from the prefabs we just attached, and attach a Laser script to the Enemy Laser parent. This will control both Lasers as one!
Now we can edit the Box Collider for the Enemy Laser parent, and make sure ‘Is Trigger’ is selected:
Into the Laser code
First we’ll add a new private bool to our Laser script global variables. This will let the script know if it is to behave as an Enemy Laser or a Player Laser.
And we’ll create a function that will change our bool from true to false:
Now to determine the inherent difference between an Enemy laser and a Player laser: movement!
The movement code for each is very similar. The differences being the Vector3 translation, and their out of bounds variable.
And now the Enemy code
Similar to our Player’s shooting function, we’ll create Global variables in our Enemy script to determine the prefab used, and a canFire and fireRate variable.
Then implement it just the same. This time, however, getting a reference to the Laser created (enemyLaser), and then using that to call the AssignEnemyLaser() function from the Laser script. Our _fireRate will also be random, so that our Enemy fires a laser in random intervals making it less predictable!
Fixing some Collision logic
Now we’ll have to create and tweak how our Laser interacts with others.
First, we’ll create an OnTriggerEnter2D function in our Laser script that happens when an Enemy Laser hits our Player:
Next we’ll jump back to our Enemy script and create a bool to determine if they are alive or not. This is necessary because we are delaying them being destroyed due to animation constraints. If we don’t utilize this bool, we would have a bug where the Enemy’s ghost would still fire lasers!
And update our Firing logic:
Now to determine when the Enemy has been destroyed:
And now our Enemies have become a little bit harder, making the game a little more challenging for our Player! This all adds to the fun!
In the next article, we’ll be giving more functionality to our Player’s Thrusters — letting them move faster by holding down a key, and visually representing how much Thruster fuel they have left!