Object Collision Detection (Bounding Box)
Flash CS4 ActionScript 3.0 Tutorial
How to Detect if an Object Hits Another Object with Flash ActionScript
Collision detection is handy when building games or other movies where you need to know if two objects have hit each other or if an object passes a specific stage location. The hit area can be specified as the object bounding box or, a point on the shape. In this example we will monitor to see if two objects collide.
A Movie Symbol with the instance name letterL_mc
A Movie Symbol with the instance name box_mc
Open a new Flash document and name the default layer Content.
Using Static Text, add a capital letter L to the stage. The letter should be 200 points and bold.
Select the text and press Cmd/b (PC- Ctrl/b) to break apart text. Another option is to choose Modify > Break Apart.
Convert the L to a Movie Symbol by pressing F8.
In the Properties panel, assign the L an instance name of letterL_mc.
Using the Rectangle tool, add a 100 pixel by 100 pixel box to the stage.
Convert the box to a Movie Symbol by pressing F8.
In the Properties panel, assign the box an instance name of box_mc.
Add a new layer called Actions.
Option double-click (PC - Alt double-click) frame one of the Actions layer.
Copy/Paste the following code to the ActionScript panel.
Publish your movie by pressing Cmd/Return (PC - Ctrl/Enter). When the box hits the bounding box for the letter L, it stops. To tighten the collision target area, see topic, Object Collision Detection (Object Pixels).
Dissecting the Code
The first four lines of the code at Step Eleven set the letter and box starting location on the stage.
The next line adds an event listener and runs the function onMove several times per second. If the project's frame rate is 18fps, then the function runs 18 times per second.
The onMove function moves the box left five pixels each time the function is run.
An if statement is added to check to see if the letter has hit the bounding box of the letterL_mc. If the box collides, the event listener is removed and "game over" appears in the Output panel.