7.15. Checking for Overlapping Movie Clips (Performing Hit Tests)


You want to find out if two movie clips are overlapping.


Use the hitTest( ) method. Or, for testing collisions between two complex shapes, create and utilize a custom hitTestOutline( ) method.


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:

// Returns true if myMovieClipA overlaps myMovieClipB, and false otherwise. This
// tests whether the bounding boxes overlap. If the shapes are nonrectangular, this
// technique may not be appropriate.

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.