Stage Coordinate Collision Detection

Stage Coordinate Collision Detection

Flash CS4 ActionScript 3.0 Tutorial

 

How to Detect if an Object Hits a Point on the Flash Stage

 

 

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 an object collides with a point on the stage.

Tutorial Elements

A Movie Symbol with the instance name letterC_mc

 

Step One

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

Step Two

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

Step Three

Convert the C to a Movie Symbol by pressing F8.

Step Four

In the Properties panel, assign the C an instance name of letterC_mc.

Step Five

Add a new layer called Actions.

Step Six

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

Step Seven

Copy/Paste the following code to the ActionScript panel.

letterC_mc.x=100;

letterC_mc.y=0;

addEventListener(Event.ENTER_FRAME, onMove);

function onMove(e:Event):void{

letterC_mc.y +=5;

if(letterC_mc.hitTestPoint(150,200,true)){

trace("game over")

}

}

Step Eight

Publish your movie by pressing Cmd/Return (PC - Ctrl/Enter). When any pixel of the lettter hits the target (x=150 and y=200), "game over" appears in the Output panel.

Step Nine

Change the word true to the word false in the if statement. Now the hit test is based on the bounding box that surrounds the entire letter.

Step Ten

Publish your movie again by pressing Cmd/Return (PC - Ctrl/Enter). When the letter's bounding box hits the target (x=150 and y=200), "game over" appears in the output panel multiple times.

Dissecting the Code

The first two lines of the code at Step Seven set the letter's startinglocation to x = 100 and y = 0.

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 letter down five pixels each time the function is run.

An if statement is added to check to see if the letter has hit a point on the stage (x = 150 and y = 200). The true or false setting determines if Flash looks for the object's bounding box (false) or the actual pixels of the object (true).