Detect collision between two objects

July 11th, 2009 in Flash

Few lines of code that cover the technique on how you can detect collision between two objects with actionscript 3.

View DemoDownload Source

1. First watch the demo to see what we are going to create.
Create a new flash file (Actionscript 3.0) and save it as detect_collision.fla.

2. On the stage create 2 movie clips, one for the car and one for the line. Set their instance name to respectively car_mc and line_mc.

3. Create a new layer named ‘actions’ and with its first frame selected open the actions panel.
Paste the following code:

stage.addEventListener(KeyboardEvent.KEY_DOWN,moveCar);

function moveCar(evt:KeyboardEvent) {
	if (evt.keyCode == Keyboard.LEFT)  {
		car_mc.x -=8;
		if (car_mc.hitTestObject(line_mc)) {
			stage.removeEventListener(KeyboardEvent.KEY_DOWN,moveCar);
		}
	}
}

4. Explainations We add a KeyboardEvent listener to the stage that call the moveCar function when the KEY_DOWN event is dispatched. In the moveCar function we check if the left arrow of the keyboard is down and if so we decrement the x property of the car. Next we call the hitTestObject method to evaluate if the car overlaps with the line. If so, we remove the KEY_DOWN event listener from the stage so that the car can’t be moved.

5. Test your movie to see it in action.

  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Twitter


What you think ...

(2 Comments)

+ Add a Comment
  1. Collision Detection in AS3 | FREE flash tutorials | The Dude
    Aug 20th, 2009

    [...] View tutorial // [...]

  2. Subash
    Jan 11th, 2010

    the tutorial is really great, i was wondering as the finish line for the car is one object, what if i need to make the car smashing to a tree for a game which am developing, i have a tree movieclip on stage as you have “line_mc” and instance name as tree_mc, wheni set the same tree by manually duplicating and placing where i want and use the hittestobject it works only for one tree not for multiple trees, could you suggest on this

    thx

Leave a Comment

Name (required)

E-mail (required, will not be published)

Website