Nick
Nick

Reputation: 3435

Actionscript 3.0 MovieClip hit test

I have a MovieClip. It represents animation of jumping monster. For clearness, let's pretend there are only 2 frames: the first one occupies top left rectangle (x = 0, y = 0, w = 70, h = 70) and the second one occupies (x = 100, y = 0, w = 70, h = 70). So monster jumps from left to the right. And position of MovieClip itself is constantly = (0, 0). I'd like to fire some event when monster is clicked by mouse.

For some reason, I have stage mouse listener, not monster mouse listener. I wrote this code:

stage.addEventListener(MouseEvent.CLICK, onClick);

private final function onClick(e:MouseEvent):void
{
    const clickPos:Point = new Point(e.stageX, e.stageY);
    // having monster:MovieClip, how do I check hitting it?
    // code below doesn't work
    // const r:Rect = new Rectangle(monster.x, monster.y,
    //                              monster.width, monster.height);
    // const hitTest:Boolean = r.containsPoint(stagePoint);
    // because r is always (0,0,70,70)
}

Upvotes: 0

Views: 1789

Answers (1)

Jason Sturges
Jason Sturges

Reputation: 15955

Instead of stage.addEventListener, apply that listener to your monster:MovieClip to call your onClick handler when the monster is clicked with the mouse.

monster.addEventListener(MouseEvent.CLICK, onClick);

You can hit-test your monster against a point, passing in x and y coordinate. There is a third parameter of "shapeFlag" to check against the actual pixels of the object (true) or the bounding box (false).

monster.hitTestPoint(x, y, true);

Or, hit test against another display object

monster.hitTestObject(obj);

Upvotes: 1

Related Questions