2D Galaxy Shooter: Enemies Fire Back! Time to Escape!
It was unexpected! We were piloting sector-z894, and they started firing back at us! We had no choice but to escape!
So the enemies can fire back at us. And we now have a functional “Escape” key if we want to quit the application or restart the scene.
Having the enemies shoot took some trial and error.
I started implementing the enemy shooting logic in a coroutine! It worked at the end, but it was long and messy. I wanted something cleaner. So I went with the idea of a cool-down system. I wrote about it here if you are interested in reading it.
if(Time.time > _canFire)
{
_fireRate = Random.Range(3f, 6f);
_canFire = Time.time + _fireRate; var enemeyLaser = Instantiate(_laserPrefab, transform.position, Quaternion.identity); Projectile[] lasers = enemeyLaser.GetComponentsInChildren<Projectile>(); for (int i = 0; i < lasers.Length; i++)
{
lasers[i].IsEnemyLaser();
}
}
There are many ways to go about it. That is why I decided to go with the coroutine route at first. But sometimes it’s better off to stick with something you know!
When I instantiate the laser prefab and cache it to the variable enemyLaser, I go right ahead to access the laser’s projectile script. This will enable me to call a function that will enable the projectile to be identified as the enemy.
With the enemy able to shoot, I had to refactor and modularize the projectile script. The script was meant to shoot upwards. Now it is modularized so that the enemies can shoot downwards.
private void Update()
{
if (!_isEnemyLaser)
MoveUp();
else
MoveDown();
}
I have also implemented a Pause Menu when hitting the escape key. The pause menu will pop up, and we can either choose to restart the scene or quit the application.
It has been a cool ride so far! The next article will be about how to deploy a game on PC/MAC and web GL!
Thank you for your time!