0
votes

I have 2 classes, the one is the main, and the other let's say Tank class, so where I need to define this events:

addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
addEventListener(KeyboardEvent.KEY_UP, onKeyUp);

        private function onKeyDown(e:KeyboardEvent):void{

            trace(e.keyCode);


        }

        private function onKeyUp():void{


            trace(e.keyCode);

        }

I don't know why but when I define this function and add the listeners in the Tank class, and then create the Tank object in the Main class the addChild(tank), that event doesn't work, can you give me an advice on where is better and neccesary to put those events?

2

2 Answers

1
votes

You have to add listeners to the stage. Stage is a global object which appears after Event.ADDED_TO_STAGE event in every DisplayObject. You can listen this event in your tank class or in the Main, but the best solution is to create some global singltone class which encapsulates keyboard events and use it everywhere. Therefore you can disable keyboard at all or you can implement that user change keys.

public class KeyboardController extends EventDispathcer{

    public static const inst:KeyboardController  = new KeyboardController ();

    public static const STOP_TANK:String = "stopTank";

    public function init(stage:Stage):void{
        //init in you Main
        //add listeners
    }

    private function stopTankKeyHandler(event:KeyboardEvent):void{
        //who manages tank will listen thisevent:KeyboardController.inst.addEventListener(KeyboardController.STOP_TANK, someHandler);
        dispatchEvent(new Event(STOP_TANK));
    }
}
0
votes

You should define them on stage:

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);