Learning ActionScript 2.0 in Adobe Flash |
|
|
|
| Creating Interaction with ActionScript > Creating interactivity and visual effects > Detecting collisions | |||
The hitTest() method of the MovieClip class detects collisions in a SWF file. It checks to see if an object has collided with a movie clip and returns a Boolean value (true or false).
You would want to know whether a collision has occurred either to test if the user has arrived at a certain static area on the Stage, or to determine when one movie clip has reached another. With hitTest(), you can determine these results.
You can use the parameters of hitTest() 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. When you specify x and y, hitTest() returns true if the point identified by (x, y) is a non-transparent point. When a target is passed to hitTest(), the bounding boxes of the two movie clips are compared. If they intersect, hitTest() returns true. If the two boxes do not intersect, hitTest() returns false.
Move the pointer over the shape in the SWF file to test the collision. The results of the hitTest() method are returned in the text field.
You can also use hitTest() to test a collision between two movie clips.
To test the collision, drag the car movie clip so that it touches the parking area movie clip. The results of the hitTest() method are returned in the text field.
The following example shows how to detect a collision between a mouse and movie clips on the Stage.
To detect a collision between a movie clip and the mouse pointer:
this.createEmptyMovieClip("box_mc", 10);
with (box_mc) {
beginFill(0xFF0000, 100);
moveTo(100, 100);
lineTo(200, 100);
lineTo(200, 200);
lineTo(100, 200);
lineTo(100, 100);
endFill();
}
this.createTextField("status_txt", 999, 0, 0, 100, 22);
var mouseListener:Object = new Object();
mouseListener.onMouseMove = function():Void {
status_txt.text = _level0.hitTest(_xmouse, _ymouse, true);
}
Mouse.addListener(mouseListener);
The value true appears whenever the pointer is over a non-transparent pixel.
To perform collision detection on two movie clips: car_mc and area_mc.
this.createTextField("status_txt", 999, 10, 10, 100, 22);
area_mc.onEnterFrame = function() {
status_txt.text = this.hitTest(car_mc);
};
car_mc.onPress = function() {
this.startDrag(false);
updateAfterEvent();
};
car_mc.onRelease = function() {
this.stopDrag();
};
Whenever the bounding box of the car intersects the bounding box of the area, the status is true.
For more information, see hitTest (MovieClip.hitTest method) in the ActionScript 2.0 Language Reference.
|
|
|
|