When MouseEnabled fails

June 16, 2010 Actionscript AS3 Troubleshooting Flash
Some problems in Flash can be a real pain sometimes. For instance in the following case.

Having a sprite that includes another sprite, but only the parent sprite should be able to recieve mouse events. The child sprite would only be used to be painted on in the drawLine function which is called on a regular basis. A simplified version would look something like this:
public class Tag extends Sprite{
private var _canvas:Sprite;

public function Tag() {
_canvas = new Sprite();
addChild(_canvas);
_canvas.mouseEnabled = false;

addEventListener(MouseEvent.MOUSE_OVER, onMouseOver);
}

private function onMouseOver(e:MouseEvent):void {
// Do stuff
}

private function drawLine():void{
var targetX:Number = 120;
var targetY:Number = 10;

_canvas.graphics.clear();
_canvas.graphics.lineStyle(3, 0x888888, 0.75);
_canvas.graphics.moveTo(0, 0);
_canvas.graphics.lineTo(targetX, targetY);
}
}
Looks pretty straight forward? _canvas.mouseEnabled is set to false, and that should remove the MouseEvent.MOUSE_OVER from being triggered when the mouse is over the child, right? WRONG!

Eventhough _canvas.mouseEnabled is disabled it will fire the event as the graphics of _canvas still resides in the parent sprite. The way to solve this is to check which object triggered the event by changing the onMouseOver function to:
  private function onMouseOver(e:MouseEvent):void {
if (e.target != this)
return;
// Do stuff
}
Is the target the main sprite? If not bail out of the event handler. Another approach would be to use the hitRect attribute of the main sprite.

Related posts: