Home > Articles

  • Print
  • + Share This
This chapter is from the book

Lesson 21: Detecting Collisions

In games, things collide, usually with disastrous results for one or both objects colliding. You need to be able to write code that detects whether two objects collide, or whether the cursor location collides with an object.

In Flash, the primary way to determine whether two objects collide, or an object is covering a certain point on the screen, is to use the hitTest function. You can feed the hitTest function either the location of a point or another movie clip.

Let's start with testing for collision with a point. Suppose you have a movie clip on the screen and you want to determine whether the user's cursor is over it. You can attach this code to the movie clip:

onClipEvent (enterFrame) {
  if (this.hitTest(_root._xmouse,_root._ymouse,true)) {
    this._x = int(Math.random()*550);
    this._y = int(Math.random()*400);

By using this.hitTest(), you are asking for the function hitTest to be used on the current movie clip. The three parameters passed into it are the horizontal location of the mouse, the vertical location of the mouse, and a true. This last parameter determines whether Flash uses the bounding box around the movie clip as the area for collision detection, or whether only the exact shape of the object is used. This code uses the latter parameter option by indicating true.

Example file: Runaway.fla

You can see this code in action in the sample movie Runaway.fla. When you move the cursor over the movie clip, it jumps to a random spot on the screen.

Example file: Collision.fla

To determine whether two movie clips intersect, you can instead use a single parameter—a pointer to the second movie clip—to see whether they both collide. In the movie Collision.fla, two movie clips are on the Stage. The larger is named "target" and the smaller is named "bullet." There is also an "actions" movie clip just off the Stage. The following code is attached to it:

onClipEvent (enterFrame) {

  // see if the bullet hit the target
  if (_root["target"].hitTest(_root["bullet"])) {

    // collision, so target grows
    _root["target"]._xscale += 5;
    _root["target"]._yscale += 5;

    // bullet resets
    _root["bullet"]._x = 350;

  } else {

    // no collision, continue to move bullet
    _root["bullet"]._x -= 5;

This code moves the bullet to the left 5 pixels at a time. When the two movie clips collide, the target grows slightly by having its scale increased by 5%. The bullet's horizontal position is reset so it can begin its approach again.

So far, you have learned how to scale a movie clip and change its position. Next, you'll learn how to change a movie clip's appearance in a more drastic way.

  • + Share This
  • 🔖 Save To Your Account