AS3: defining hit area

2019-02-16 19:58发布

问题:

I have a movieclip which contains a bitmap and I wan't to increase the hit area. I understand I can add a transparent shape behind it but this is to be compiled through air for ios and I don't want to cause unnecessary redraws.

Is there a way to define a rectangle as the hit area or another solution perhaps?

回答1:

There is a special hitArea field for that purposes.

  const MOUSE_ZONE_SIZE:Number = 10;
  const hitArea:Sprite = new Sprite()
  hitArea.graphics.beginFill( 0xFFFFFF );
  hitArea.graphics.drawRect( -MOUSE_ZONE_SIZE, -MOUSE_ZONE_SIZE, MOUSE_ZONE_SIZE* 2, MOUSE_ZONE_SIZE* 2 );
  hitArea.mouseEnabled = false;
  hitArea.visible = false;
  hitArea.x = bitmap.x
  hitArea.y = bitmap.y
  bitmap.hitArea = hitArea;
  addChild( bitmap );
  addChild( hitArea );

Unfortunately even if you override hitTest* function of InteractiveObject they will not be used for mouse-events dispatching :( If somebody knows how to force Flash to use overridden methods - I'd like to know it too.



回答2:

You could also create a button with Bitmap inside it then define the hitArea. It essentially does the same thing that Ilya did in code. However when you add the new instance of the button to the stage you will be able to apply MouseEvents to it.

Pretty pictures :)

package{
import flash.display.MovieClip;
import flash.events.MouseEvent;

public class main extends MovieClip
{
    public function main()
    {
        var btn:button = new button();
        btn.addEventListener(MouseEvent.CLICK, clicked);
        this.addChild(btn);
    }

    private function clicked(e:MouseEvent):void{
        trace("Clicked");
    }

}
}

The problem is this will increase the amount of memory and power to do on the iOS so it's really a horse a piece... :(