views:

581

answers:

3

Hi,

I encountered this really weird situation, I have this bar and I addEventListener to it, so when the bar's clicked, trace localX

private function _barClicked($e:MouseEvent):void {
      trace($e.localX)
}

The weird thing is that, when clicking at the same spot, sometimes it jump to a wrong number which I can't figure out why, I traced the width of the bar, and it's the right value, the localX is just giving me random numbers. Has anyone ever ran into this problem? Thanks!

+3  A: 

Hmmm, strange

I've tried a simple scenario where I have a rectangle named 'bar' and pasted your listener for the CLICK event, then tried the MOUSE_DOWN event. Both worked fine. I didn't get random values.

My guess is your bar clip contains other objects inside and you might get values from children of bar, not bar itself. Not sure though, it's just a guess.

You could try to make sure that your values come from $e.currentTarget as $e.target might change depending on: your clip and how many children it holds, position of the click and event phase.

Try

private function _barClicked($e:MouseEvent):void {
      trace($e.currentTarget.mouseX);
}

Hope it helps!

George Profenza
I ran into this scenario, and it was exactly because of the reason George points out. However, a colleague pointed out that the mouse position could have moved between the time of the event and the time that you query mouseX on the currentTarget. So in situations where you need to know the exact position where the event occurred, it is better to calculate the local coordinates using e.currentTarget.globalToLocal(new Point(e.stageX, e.stageY)).
Kevin Condon
A: 

I was having the same problem, and Kevin Condon solution from the comment above helped my problem. I am just posting it here, because I almost missed it in the comment.

private function _barClicked($e:MouseEvent):void {
     var coord:Point = $e.currentTarget.globalToLocal(new Point($e.stageX, $e.stageY));
     trace(coord.x);
}

Thanks Kevin.

UberNeet
A: 

Just wanted to note a variation on this problem for those for whom the above is not working.

I was having the same issue - localX showing odd values. Mine weren't random, just far lower than what I expected. I.e., click on the far right of the sprite and get only 17.2, event though the width was reporting as 160.

What I found was that my instance was a scaled version of a symbol who's native width was much less.

Once I set it up so that the symbol and the instance had the same width, I started getting the right values.

Hope this helps someone.

evanmcd