Creating Interaction with ActionScript > Detecting collisions
Detecting collisions
You can use the hitTest
method of the MovieClip object to detect collisions in a movie. The hitTest
method checks to see if an object has collided with a movie clip and returns a Boolean value (true
or false
). You can use the parameters of the hitTest
method to specify the x and y coordinates of a hit area on the Stage, or use the target path of another movie clip as a hit area.
Each movie clip in a movie is an instance of the MovieClip object. This allows you to call methods of the object from any instance, as in the following:
myMovieClip.hitTest(target);
You can use the hitTest
method to test the collision of a movie clip and a single point.
Move the mouse over the shape in the movie to test the collision. The results of the hitTest
are returned in the text field.
You can also use the hitTest
method to test a collision between two movie clips.
To test the collision, drag one movie clip so that it touches the other. The results of the hitTest
are returned in the text field.
To perform collision detection between a movie clip and a point on the Stage:
1 | Select a movie clip on the Stage. |
2 | Choose Window > Actions to open the Object Actions panel. |
3 | Double-click trace in the Actions category in the toolbox. |
4 | Select the Expression check box and enter the following in the Expression box: |
trace (this.hitTest(_root._xmouse, _root._ymouse, true); |
|
This example uses the _xmouse and _ymouse properties as the x and y coordinates for the hit area and sends the results to the Output window in Test-Movie Mode. You can also set a text field on the Stage to display the results or use the results in an if statement. |
|
5 | Choose Control > Test Movie and move the mouse over the movie clip to test the collision. |
![]() |
To perform collision detection on two movie clips:
1 | Drag two movie clips to the Stage and give them the instance names mcHitArea and mcDrag. |
2 | Create a text field on the Stage and enter status in the Text Options Variable box. |
3 | Select mcHitArea and choose Window > Actions. |
4 | Double-click evaluate in the toolbox. |
5 | Enter the following code in the Expression box by selecting items from the toolbox: |
_root.status=this.hitTest(_root.mcDrag); |
|
6 | Select the onClipEvent action in the Script window and choose enterFrame as the event. |
7 | Select mcDrag and choose Window > Actions. |
8 | Double-click startDrag in the toolbox. |
9 | Select the Lock Mouse to Center check box. |
10 | Select the onClipEvent action in the Script window and choose the Mouse down event. |
11 | Double-click stopDrag in the toolbox. |
12 | Select the onClipEvent action in the Script window and choose the Mouse up event. |
13 | Choose Control > Test Movie and drag the movie clip to test the collision detection. |
![]() |
For more information about the hitTest
method, see its entry in the ActionScript Dictionary.