7.15. Checking for Overlapping Movie Clips (Performing Hit Tests)
Problem
You want to find out if two movie clips are overlapping.
Solution
Use the hitTest( )
method. Or,
for testing collisions between two complex
shapes, create and utilize a custom hitTestOutline(
)
method.
Discussion
The hitTest( )
method enables you to determine
one of three things:
Whether any point within the bounding box of one movie clip overlaps any point in the bounding box of another movie clip
Whether a specific coordinate is within the bounding box of a movie clip
Whether a specific coordinate is within the outline of a movie clip’s shape
The easiest way to test whether a movie clip overlaps another clip is
to call hitTest( )
from one movie clip instance
and pass it a reference to the other movie clip instance:
// Returnstrue
ifmyMovieClipA
overlapsmyMovieClipB
, andfalse
otherwise. This // tests whether the bounding boxes overlap. If the shapes are nonrectangular, this // technique may not be appropriate. myMovieClipA.hitTest(myMovieClipB);
Here is a working example that draws a circle and a rectangle. Then,
using the startDrag( )
method, the code causes
the circle movie clip to follow the pointer. Using an
onEnterFrame( )
method in conjunction with
hitTest( )
, the code continually checks whether
the circle overlaps the rectangle. If you test the example, you can
see that there are times when the hit test returns
true
even though the circle shape does not overlap the rectangle. This is because the circle’s ...
Get Actionscript Cookbook 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.