Object Collision Detection (Object Pixels)
Flash CS4 ActionScript 3.0 Tutorial
How to Detect if an Object Hits Another Object Using 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. Since the letter object has an oversize boundary, we will break the target into two smaller targets.
A Movie Symbol with the instance name letterL_mc
Inside the letterL_mc will be two nested Movie Symbols, side_mc and bottom_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.
Double-click the letter to edit the symbol and draw a marquee with the Selection tool to select the side of the letter.
Press F8 and to convert the side to a Movie Symbol.
In the Properties panel, assign the new an instance name of side_mc.
Double-click the remaining portion of the letter to select it.
Press F8 and to convert the bottom to a Movie Symbol.
In the Properties panel, assign the new an instance name of bottom_mc.
Return to the main timeline and use the Rectangle tool to 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 at the top 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 nested movie, side_mc or bottom_mc, it stops.
Dissecting the Code
The first four lines of the code at Step Seventeen 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 either the side_mc or bottom_mc. If the box collides, the event listener is removed and "game over" appears in the Output panel.