Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Replace the current Update() method of the AsteroidManager class:
Public Sub Update(gameTime As GameTime) For Each asteroid as Sprite in Asteroids asteroid.Update(gameTime) If Not isOnScreen(asteroid) Then asteroid.Location=randomLocation() asteroid.Velocity=randomVelocity() End If Next For x as Integer = 0 to Asteroids.Count -1 For y as Integer = x+1 to Asteroids.Count -1 If (Asteroids(x).IsCircleColliding( Asteroids(y).Center, Asteroids(y). CollisionRadius)) Then BounceAsteroids(Asteroids(x), Asteroids(y)) End If Next Next End Sub
Execute the game and watch the Asteroids bounce off of each other.
Close the game window.
Each asteroid is updated just as before. Afterwards, however, two nested loops process each asteroid in the list, checking for collisions with all of the other Asteroids. If two Asteroids collide, they are both passed to the BounceAsteroids() method. The second loop is written to minimize the collision comparisons by only checking Asteroids with a higher index number than the current asteroid. When the first asteroid is checked, it is compared with all of the remaining Asteroids, so when the second asteroid is processed, there is no need to check against the first asteroid again as that has already been done and responded to.