XNA GameStudio 2.0
Creating An Enemy Squadron

Now that we can fire bullets, we need something to aim at. The process of drawing enemies on the screen is not unlike that which we followed to draw bullets. We have a set number of enemies that we redraw on the screen each time one is removed.

Stage 1 - Fields

We are going to need the following fields. It should be obvious what we are doing with the first 4 fields. The randGen field will be used to generate random positions and velocities for our enemies.

GameObject[] enemies;
const int maxEnemies = 5;
const float minEnemyVelocity = 1.0f;
const float maxEnemyVelocity = 5.0f;
Random randGen = new Random();

Stage2 - Load Content

We add some lines of code to the LoadContent() method of the main game class. Again, this is similar to what we have done previously.

enemies = new GameObject[maxEnemies];
for (int i = 0; i < maxEnemies; i++)
{
   enemies[i] = new GameObject(Content.Load<Texture2D>("Sprites\\invader"));
}

Stage 3 - Write UpdateEnemy Method

The update routine for the enemies is shown below. If an enemy is alive, we update its position and check that it is still on screen. If it isn't, we set alive to false so that we can recreate the enemy on the right hand side of the screen again. The else part of this statement recreates the enemy with a random starting height and a random velocity.

private void UpdateEnemies()
{
   Rectangle viewPortRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
   foreach (GameObject enemy in enemies)
   {
      if (enemy.alive)
      {
         enemy.position += enemy.velocity;
         if (!viewPortRect.Contains(new Point((int)enemy.position.X,(int)enemy.position.Y)))
         {
            enemy.alive = false;
         }
      }
      else
      {
         enemy.alive = true;
         enemy.position = new Vector2(viewPortRect.Right, MathHelper.Lerp((float)viewPortRect.Height * 0.1f,(float)viewPortRect.Height*0.5f,(float)randGen.NextDouble()));
         enemy.velocity = new Vector2(MathHelper.Lerp(-minEnemyVelocity, -maxEnemyVelocity, (float)randGen.NextDouble()), 0);
      }
   }
}

You need to add a call to this method in the Update() method of the class.

UpdateEnemies()

Stage 4 - Draw The Enemies

Our final job is to make sure that all enemies that are alive will be drawn on the screen in their correct places. As ever, we do this in the Draw() method of the main game class.

foreach (GameObject enemy in enemies)
{
   if (enemy.alive)
   {
      spriteBatch.Draw(enemy.sprite, enemy.position, Color.White);
   }
}

Test the game at this stage and correct and errors that have cropped up. The enemies won't disappear when you shoot them yet. Monkey around with the min and max velocity and some of the other figures until the enemies behave as you want them to.