mercredi 4 janvier 2017

Can I access the stage dimensions in AS3 before the Stage class is instantiated?

I have a class that relies on the stage width in its constructor. I don't need to construct it when the app first loads, but I still get the 1009 error (attempted access of null object) because the stage hasn't been instantiated yet and I guess when it compiles it checks all constructors to make sure that everything is available at compile time... fine.

I could just use variables to hold that width value and then update that value when the stage changes size, but I'd like a more elegant approach. Is there a way to access the stage properties even before it is instantiated? Or is there another way to do this?

I'm compiling for AIR for desktop using Flex SDK and coding in FlashDevelop.

My obligatory code:

public class MouseSenseWindow extends Sprite {
    private var _sensitivity:Number = 1;
    private var _bounds:Rectangle = new Rectangle(0,0,stage.stageWidth,stage.stageHeight);
    public function MouseSenseWindow(sense:Number):void{
        sensitivity = sense;
        drawBox();
        addEventListener(MouseEvent.MOUSE_MOVE, mouseHit);
    }


    private function mouseHit(me:MouseEvent):void {
        removeEventListener(MouseEvent.MOUSE_MOVE, mouseHit);
        grab();
    }


    private function drawBox():void{
        graphics.clear();
        graphics.beginFill( 0, 0 );
        graphics.drawRect( 0, 0, stage.stageWidth / _sensitivity, stage.stageHeight );
        graphics.endFill();
    }


    public function grab():void{
        startDrag(false, _bounds);
    }


    public function get sensitivity():Number{return _sensitivity;}
    public function set sensitivity(s:Number):void{
        _sensitivity = s;
        drawBox();
    }
} //end class

Aucun commentaire:

Enregistrer un commentaire