Search code examples
flashactionscriptlistenerkeyeventstarling-framework

Starling keyevents


So anyone any idea why it does not working? I want to listen keyevents with my starling class, do I need to focus and if yes how can I do that? Here's a Main class, this is the document class:

package
{
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
    import starling.core.Starling;

public class Main extends Sprite{
    private var starling:Starling

    public function Main(){         
        if (stage)
            init();
        else
            addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
    }

    private function init(e:Event = null):void{
        removeEventListener(Event.ADDED_TO_STAGE, init);                        
        starling = new Starling(ScreenCoorder, stage);
        starling.start();       
    }
}

}

And the screencorder class (starts by starling):

package  
{

import starling.display.Sprite;
import starling.events.Event;
import starling.events.KeyboardEvent;

public class ScreenCoorder extends Sprite{

    public function ScreenCoorder() {
        super();
        addEventListener(Event.ADDED_TO_STAGE, init);
    }

    private function init():void {
        removeEventListener(Event.ADDED_TO_STAGE, init);
        this.addEventListener(KeyboardEvent.KEY_DOWN, onDown);
    }       

    public function onDown(e:KeyboardEvent):void {
        trace("so serious");
    }   
}

}


Solution

  • Starling Sprite's don't support keypresses, you need to add the listener to the native Stage object like so..

    this.nativeStage.addEventListener(KeyboardEvent.KEY_DOWN, onDown);