Object Collision Detection (Bounding Box)

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.

Tutorial Elements

A Movie Symbol with the instance name letterL_mc

A Movie Symbol with the instance name box_mc


Step One

Open a new Flash document and name the default layer Content.

Step Two

Using Static Text, add a capital letter L to the stage. The letter should be 200 points and bold.

Step Three

Select the text and press Cmd/b (PC- Ctrl/b) to break apart text. Another option is to choose Modify > Break Apart.

Step Four

Convert the L to a Movie Symbol by pressing F8.

Step Five

In the Properties panel, assign the L an instance name of letterL_mc.

Step Six

Using the Rectangle tool, add a 100 pixel by 100 pixel box to the stage.

Step Seven

Convert the box to a Movie Symbol by pressing F8.

Step Eight

In the Properties panel, assign the box an instance name of box_mc.

Step Nine

Add a new layer called Actions.

Step Ten

Option double-click (PC - Alt double-click) frame one of the Actions layer.

Step Eleven

Copy/Paste the following code to the ActionScript panel.





addEventListener(Event.ENTER_FRAME, onMove);

function onMove(e:Event):void{

box_mc.x -=5;


removeEventListener(Event.ENTER_FRAME, onMove);

trace("game over");



Step Twelve

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.


Lynda.com career skills