XNA GameStudio 2.0
Collisions

The last basic thing that we need to do to get this game going is to deal with the collisions between bullets and enemies. When a bullet hits an enemy, we need to make sure that both game objects are removed from the screen.

We will make the changes that we need to the UpdateBullets() method.

private void UpdateBullets()
{
   foreach (GameObject b in bullets)
   {
      if (b.alive)
      {
         b.position += b.velocity;
         Rectangle viewPortRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
         if (!viewPortRect.Contains(new Point((int)b.position.X, (int)b.position.Y)))
         {
            b.alive = false;
            continue;
         }
         Rectangle bulletRect = new Rectangle((int)b.position.X, (int)b.position.Y, b.sprite.Width, b.sprite.Height);
         foreach (GameObject e in enemies)
         {
            if (e.alive)
            {
               Rectangle enemyRect = new Rectangle((int)e.position.X, (int)e.position.Y, e.sprite.Width, e.sprite.Height);
               if (enemyRect.Intersects(bulletRect))
               {
                  b.alive = false;
                  e.alive = false;
                  break;
               }
            }
         }
      }
   }
}