Game Development Reference
In-Depth Information
Figure 5-9. Collision detection method comparison
When Bitmap support was included in ActionScript, it included a function for the BitmapData
object named hitTest() . It is similar to MovieClip.hitTest() in name only.
BitmapData.hitTest() tests for collisions based on the actual pixels in an image, not on bounding
boxes. If you have an image with a transparent color, it will ignore that color when detecting
collisions. See Figure 5-9, bottom section. Since we spent the time to create BitmapData for each
of our objects, we can now use those objects to detect collisions.
There is one drawback to using BitmapData.hitTest() . While this function tests every pixel of a
Bitmap image for a collision with every pixel of another Bitmap image, the Bitmap data to perform
this operation is created once but not updated with any kind of transform (i.e., rotation). If you do
try to transform an image with something like a rotation, the Bitmap data will remain in its original
state, and false or incorrect hits will occur. The good news is that you can update the BitmapData
manually when you transform an image (we will discuss this type of operation later in this topic).
Since we don't have to rotate any images or do any other kinds of transform on them, we do not
need to worry about this for Flak Cannon. We can use the function as is.
Now, let's move on to the checkCollisions() function. Whenever you need to test against
multiple types of objects, it is a good idea to try to group these objects so that, if possible, they
can be tested at the same time. You can do this by nesting loops that iterate through the various
lists of object. If these loops are nested properly, you can maximize the number of collisions
checked per loop and minimize the number of loops that need to be completed. However, there is
a point at which multiple nested loops become hard to maintain. We have taken a conservative
approach in Flak Cannon. We have created three distinct loops, each illustrating a different set of
collisions. There are ways we could have optimized this function further, but we would rather the
code be clear to you, instead of just being tricky with some nested loops.
We are going to test three explicit bitmap collisions in this function grouped the following ways:
Enemy hitting Flak or BonusPlane hitting Flak
Enemy hitting Ship
Search WWH ::




Custom Search