Search code examples
actionscript-3mouseeventgesture

event.localX of a MovieClip regardless of any other DisplayObject over/under/inside


Here is an example:

var table:Table = new Table();
stage.addChild(table);
//table covers the whole stage
for (var i:int = 0; i<= 10; i++){
  var book:Book = new Book();
  book.x = Math.random() * stage.stageWidth;
  book.y = Math.random() * stage.stageHeight;
  if (Math.random() < .5){
    stage.addChild(book)
  }
  else {
    table.addChild(book)
  }

stage.addEventListener(MouseEvent.CLICK, clicked);

function clicked(event:MouseEvent){
trace(event.localX, event.localY);
}

what i need here is the localX or localY OF THE TABLE, not anything else.

so the general question is "how to return event.localX of a certain MovieClip regardless of any other DisplayObject over/under/inside it, without setting the mouseChildren to false (as I need them to be enabled)"


Solution

  • You can use DisplayObject's globalToLocal method to convert a Point from being relative to the stage to being relative to the table object.

    function clicked(event:MouseEvent){
        var globalPt:Point = new Point(event.stageX, event.stageY); 
        var tablePt:Point = table.globalToLocal(globalPt);
        trace(tablePt.x, tablePt.y);
    }