Online Book Reader

Home Category

HTML5 Canvas [158]

By Root 6438 0
of the rocks. The player does not need a label because there is only a single instance of the player. The saucers and saucerMissiles will follow the same logic as missiles. If there is a collision between one and a rock, break back to their respective labels after removing the objects from their respective arrays.

Once we have checked the rocks against all the other game objects, check the playerMissiles against the saucers using the same basic logic of loop labels, looping backward through the arrays, and breaking back to the labels once objects are removed.

Check the saucerMissiles against the player in the same manner.

Over the years, we have found this to be a powerful way to check multiple objects’ arrays against one another. It certainly is not the only way to do so. If you are not comfortable using loop labels, you can employ a method such as the following:

Add a Boolean hit attribute to each object and set it to false when an object is created.

Loop through the rocks and check them against the other game objects. This time the direction (forward or backward) through the loops does not matter.

Before calling the boundingBoxCollide() function, be sure that each object’s hit attribute is false. If not, skip the collision check.

If the two objects collide, set each object’s hit attribute to true. There is no need to remove objects from the arrays at this time.

Loop though playerMissiles and check against the saucers, and then loop through the saucers to check against the player.

When all the collision-detection routines are complete, reloop through each object array (backward this time) and remove all the objects with true as a hit attribute.

We have used both methods—and variations—on each. While the second method is a little cleaner, this final loop through all of the objects might add more processor overhead when dealing with a large number of objects. We will leave the implementation of this second method to you as an exercise, in case you wish to test it.

The Geo Blaster Basic Full Source

Example 8-12 shows the entire set of code for our game. You can download this and the entire set of example files from the book’s website.

Example 8-12. The Geo Blaster Basic full source listing

Geo Blaster Basic Game