Time for action – updating and drawing shots

  1. Add the Update() method to the ShotManager class:
    public void Update(GameTime gameTime)
    {
        for (int x = Shots.Count - 1; x >= 0; x--)
        {
            Shots[x].Update(gameTime);
            if (!screenBounds.Intersects(Shots[x].Destination))
            {
                Shots.RemoveAt(x);
            }
        }
    }
  2. Add the Draw() method to the ShotManager class:
    public void Draw(SpriteBatch spriteBatch)
    {
        foreach (Sprite shot in Shots)
        {
            shot.Draw(spriteBatch);
        }
    }

What just happened?

Since we may be removing shots from the list, we cannot use a foreach loop to process the list during the Update() method. Looping backwards through the list allows us to process all of the shots, removing ones that have expired, without the need to track separate removal lists or restart the iteration ...

Get XNA 4.0 Game Development by Example Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.