【问题标题】:Can I track the keys pressed, using ActionScript?我可以使用 ActionScript 跟踪按下的键吗?
【发布时间】:2011-04-29 04:19:57
【问题描述】:

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

【问题讨论】:

    标签: flash actionscript keylistener


    【解决方案1】:

    我使用了我不久前制作的这个类:

    编辑:现在稍微干净了。

        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.
    

    编辑:

    当您使用 compile (ctrl+enter) 来禁用键盘快捷键(控制 -> 禁用键盘快捷键)进行测试时,这也很有帮助。

    【讨论】:

    • 为什么 Keys 会扩展 Sprite?
    • 因为 Object 没有舞台属性,因为它不是 DisplayObject。
    • @miguelSantirso 你觉得怎么样?
    • 但是,在您发布的代码中,舞台属性作为参数传递给类构造函数,所以我不明白您为什么需要扩展 Sprite...
    • 当 Keys 扩展 Sprite 时,Stage 没有被解析到构造函数 - 这只是一个修改 - 请参阅编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2020-07-05
    • 2014-03-30
    相关资源
    最近更新 更多