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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With