开发者

ActionScript3 External Class Keyboard Listener

I was trying to make a tank game in which I can move the tanks, let them shoot each other, etc... I insist on creating external classes with Flash Pro cause I am used to OOP language like Java. I created a Tank class which represents all the tanks. Here is the code of this class:

package src
{
    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;

    public class Tank extends MovieClip 
    {       
        public function Tank():void {           
            this.addEventListener(KeyboardEvent.KEY_DOWN, move);
            this.addEventListener(MouseEvent.CLICK, test);
        }
        protected function move(event:KeyboardEvent):void {
            trace("key down");
            switch (event.keyCode) {
                case Keyboard.UP: {
                    this.y += -5;                   
                    break;
                }
                case 40: {
                    this.y += 5;                    
                    break;
                }
                case Keyboard.LEFT: {
                    this.x += -5;                   
                    break;
                }
                case Keyboard.RIGHT: {
                    this.x += 5;                    
                    break;

                开发者_如何学Python}

            }
        }

    }

}

The problem is that the action listener seems never get called when I press any keys. the trace() is not called. But I tried to add a mouse listener just to test and it worked. So I guess its the Keyboard event listener class's problem? Everyone I see on the web uses stage.addEventListener(KeyboardEvent.KEY_DOWN, move) approach.

Could anyone tell me why it's not working? And are there any solutions?(only by adding external classes, please) Thank you!


Try adding your key listeners to stage.

stage.addEventListener(KeyboardEvent.KEY_DOWN, move);

Stage will always be able to detect key events when your application is in focus.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜