Flash Tutorial – Arranging a scene (Part Two) using hitTest

In the first tutorial (Arranging a scene using depths & scale) I created a scene that gives the impression that a character can move around scenery using the _y property. This tutorial explains how to stop the character moving through the scenery using hitTest.

First, create the file from the first tutorial.

In the Scene

Create a new movie clip and add a rectangular shape in it. Place this movie clip in each of your character and scenery movie clips, re-sizing it to the width of the item and the height to represent the “depth” – see diagram. Name each of the rectangular movie clips “testarea” and set the alpha to 0%.

Flash tutorial diagram

Initial Variables

Add this below the intial variables in the Actions frame.

moveAllowed = true;

Additional Code

In the mouseListener function, replace the code

_root.Character._x = _root._xmouse;
_root.Character._y = _root._ymouse;

with this code

if (_root.moveAllowed) {
_root.Character._y = _root._ymouse;
_root.Character._x = _root._xmouse;
} else {
_root.Character._x = _root._xmouse;
}
for (i=0; i<DepthArray.length; i++) {
if (_root.DepthArray[i].mcname != "Character") {
if (_root.Character.testarea.hitTest(_root[DepthArray[i].mcname].testarea)) {
_root.moveAllowed = false;
break;
} else {
_root.moveAllowed = true;
}
}
}

And so…

Here are the results