Back to Entry Page

The hitTest() Method and the Click Problem

In case you've forgotten, what we're calling the click problem stems from the fact that movie clips in Flash, unlike buttons, do not localize the mouse events mouseDown and mouseUp. These events are detected by every movie clip within your timeline that has a handler for them. To ensure that only one movie clip responds, you have to do something to determine that the user pressed the mouse button while over a particular movie clip.

We've already looked at two prior solutions to this problem: a simple script that reads mouse position and determines if it falls within the geometry of the movie clip; and a construction technique in which we use buttons installed within movie clips instead of movie clips alone.

As discussed last week in class, there is a much simpler solution. The hitTest() method can be used on any movie clip to determine if the mouse button was pressed when the cursor was within the clip's bounding rectangle. This method can be used either to test for overlap between two movie clips, or as in this case, to determine if the movie clip in question coincides with a certain point on the screen.

By specifying the current X and Y location of the cursor, which is recorded in the variables _root._xmouse and _root._ymouse, we can determine if the cursor position falls within a movie clip. Here's the code:

onClipEvent(mouseDown){
  if(this.hitTest(_root._xmouse, _root._ymouse))
    {
      [instructions to be executed on a good hit];
    }
}

As you can see, this solution requires only a single if test. It's still annoying that we have to perform this test for movie clips (but not for buttons), but at least there's a relatively simple fix.

This note supersedes last week's, in which I suggested using an invisible movie clip to track the cursor. The procedure outlined here is much easier.

Thanks to Drew Heles for bringing this technique to light.


University of Baltimore Logo

Copyright © 2002 School of Information Arts and Technologies