Time for action – enemy shots
To implement how the enemy flying saucer fires shots, perform the following:
1. Add the following fields to the
MarsRunnerPlayScreen
class:float enemyShotCooldown = 3.0f; float enemyShotTimer = 0.0f; int enemyShotChance = 2;
2. In the
Update()
method of theMarsRunnerPlayScreen
class, determine if the enemy should fire a shot by adding the following code just after theplayerShotTimer
value has been incremented:if (enemy.IsOnScreen && !enemy.IsDestroyed) { if (enemyShotTimer < enemyShotCooldown) { enemyShotTimer += elapsed; } else { if (random.Next(0, 100) < enemyShotChance) { FireEnemyShot(); enemyShotTimer = 0.0f; } } }
3. Add the
FireEnemyShot()
method toHelper Methods
region of theMarsRunnerPlayScreen
class as follows:private void FireEnemyShot() { shotManager.AddEnemyShot(enemy.Position); }
4. Execute the game. Enemies will now occasionally fire shots while flying...