我可以使用ActionScript跟踪按下的键吗?

时间:2011-04-29 04:19:58

标签: flash actionscript keylistener

我可以使用ActionScript跟踪按下的键吗?

1 个答案:

答案 0 :(得分:2)

我使用了这段时间我做过的课程:

编辑:现在稍微清洁。

    package
    {
        import flash.display.Stage;
        import flash.events.KeyboardEvent;

        public class Keys extends Object
        {
            // vars
            private var _keys:Array = [];

            /**
             * Constrcutor
             * @param stg The stage to apply listeners to
             */
            public function Keys(stg:Stage)
            {
                stg.addEventListener(KeyboardEvent.KEY_DOWN, _keydown);
                stg.addEventListener(KeyboardEvent.KEY_UP, _keyup);
            }

            /**
             * Called on dispatch of KeyboardEvent.KEY_DOWN
             */
            private function _keydown(e:KeyboardEvent):void
            {
                //trace(e.keyCode);
                _keys[e.keyCode] = true;
            }

            /**
             * Called on dispatch of KeyboardEvent.KEY_UP
             */
            private function _keyup(e:KeyboardEvent):void
            {
                delete _keys[e.keyCode];
            }

            /**
             * Returns a boolean value that represents a given key being held down or not
             * @param ascii The ASCII value of the key to check for
             */
            public function isDown(...ascii):Boolean
            {
                var i:uint;
                for each(i in ascii)
                {
                    if(_keys[i]) return true;
                }

                return false;
            }
        }
    }

从这里开始很简单:创建一个键实例并使用isDown()方法。

    var keys:Keys = new Keys(stage);

    addEventListener(Event.ENTER_FRAME, _handle);
    function _handle(e:Event):void
    {
         if(keys.isDown(65)) trace('key A is held down');
    }

它甚至可以同时检查多个键:

if(keys.isDown(65, 66)) // true if 'a' or 'b' are held down.

修改

当您使用编译(ctrl + enter)进行测试以禁用键盘快捷键(控制 - >禁用键盘快捷键)时,它也会有很大帮助。