Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. Asteroid Belt Assault Lost in... > Time for action - bouncing Asteroids...

Time for action - bouncing Asteroids part 2

  1. 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
    
  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 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.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial