如何在ActionScript 3中编写KEY_DOWN处理程序?

时间:2009-07-14 21:36:11

标签: flex flash actionscript-3 action

好的,我已经尝试了8种不同的方法将关键事件放入我的代码中,但它们似乎都没有用。当有人按下班次时,有人可以告诉我如何移动这个球吗?提前谢谢

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" 
  styleName = "plain"
    xmlns="cyanprime.*" 
    layout="absolute"
    width="600"
    height="400"
    frameRate="100"
    creationComplete="initApp()">

    <mx:Script>
        <![CDATA[
            public function initApp():void
            {

                Mouse.hide();
                canvas.init();
                canvas.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
            }

            private function keyDown(event:KeyboardEvent):void
            {
                canvas.KeyDownHandler(event);
            }
        ]]>
    </mx:Script>

  <MyGameCanvas id="canvas" width="100%" height="100%" themeColor="#ff000000" />
</mx:Application>

...

package cyanprime{

    import mx.core.UIComponent;
    import mx.controls.Image;
    import flash.events.*;
    import flash.utils.*;
    import flash.display.*;
    import flash.ui.Keyboard;

    public class MyGameCanvas extends UIComponent{
        [Embed(source="player.gif")]
        private var playerImage:Class;

        private var player:DisplayObject = new playerImage();
        private var player_x:Number;
        private var player_y:Number;
        private var ticker:Timer;



        public function init():void{
            // set up player
            addChild(player);

            ticker = new Timer(10); 
            ticker.addEventListener(TimerEvent.TIMER, onTick);
            ticker.start();

        }

        public function KeyDownHandler(event:KeyboardEvent):void{
            if(event.keyCode == Keyboard.SHIFT)
            player_x += 50;
        }

        public function onTick(evt:TimerEvent):void {
        }       
    }
}

1 个答案:

答案 0 :(得分:3)

您需要将监听器添加到舞台,并在applicationComplete事件发生后(或在其处理程序中)对其进行广告

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" applicationComplete="init()">
 <mx:Script>
    <![CDATA[

    public function init():void
    {
        trace('Initialization');
        stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);    
    }

    private function keyDown(event:KeyboardEvent):void
    {
        trace(event.charCode);
    }       
    ]]>
 </mx:Script>
</mx:Application>

ref