Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 - Detecting if you clicked on an object without pressing the mouse button

Okay, in as3 when you click, the object on the highest layer will be clicked on. I want someone to press the space bar and have the objects on the screen to check to see if it is touching a point.

So I first tried hittest...

if (this.hitTest(myPoint)){ play(); }

Now the problem was objects behind other ones were thinking they were being "clicked" on.

Then after being frustrated I used Google, couldn't find anything so please anything helps.

like image 335
JoeCool11 Avatar asked Feb 24 '23 09:02

JoeCool11


2 Answers

I think this is the code you are looking for:

stage.addEventListener(KeyboardEvent.KEY_DOWN, function(e : KeyboardEvent) : void {
    if(e.keyCode == Keyboard.SPACE) {
        var objects : Array = stage.getObjectsUnderPoint(new Point(stage.mouseX, stage.mouseY));
        if (objects.length > 0) {
            var topmost : DisplayObject = objects[objects.length-1];
            trace(topmost.name);
        }
    }
});

Key is flash's getObjectsUnderPoint method.

like image 140
maxmc Avatar answered Apr 21 '23 13:04

maxmc


DisplayObjectContainer.getObjectsUnderPoint()

Be mindful getObjectsUnderPoint doesn't return DisplayObjectContainers, as evidenced here:

var mc:MovieClip = new MovieClip();
var shape:Shape = new Shape();
    shape.graphics.beginFill(0);
    shape.graphics.drawRect(0,0,5,5);
mc.addChild(shape);
var shape2:Shape = new Shape();
    shape2.graphics.beginFill(0);
    shape2.graphics.drawRect(0,0,5,5);
mc.addChild(shape2);
addChild(mc);
getObjectsUnderPoint(new Point(1,1)); // returns [object Shape],[object Shape]

You can use the parent property of returned DisplayObjects to find a DisplayObjectContainer...

var containerBeingLocated:Sprite;

for each (var obj:DisplayObject in objectsUnderPoint) {
    if (isWithin(obj, containerBeingLocated)) {
        trace('container located');
    }
}

function isWithin ($obj:DisplayObject, $container:DisplayObjectContainer):Boolean {
    while ($obj) {
        if ($obj === $container) {
            return true;
        } else {
            $obj = $obj.parent;
        }
    }
    return false;
}
like image 21
Pup Avatar answered Apr 21 '23 12:04

Pup