Time for action – bouncing asteroids – part 2

  1. Replace the current Update() method of the AsteroidManager class:
    public void Update(GameTime gameTime)
    {
        foreach (Sprite asteroid in Asteroids)
        {
            asteroid.Update(gameTime);
            if (!isOnScreen(asteroid))
            {
                asteroid.Location=randomLocation();
                asteroid.Velocity=randomVelocity();
            }
        }
    
        for (int x = 0; x < Asteroids.Count; x++)
        {                
            for (int y = x + 1; y < Asteroids.Count; y++)
            {
                if (Asteroids[x].IsCircleColliding(
                    Asteroids[y].Center, Asteroids[y]. CollisionRadius))
                {
                    BounceAsteroids(Asteroids[x], Asteroids[y]);
                }
            }
        }
    }
  2. Execute the game and watch the asteroids bounce off of each other.
  3. Close the game window.

What just happened?

Each asteroid is updated just as before. Afterwards, however, two nested loops process ...

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.