简体   繁体   English

如何检测Flash游戏中的按住键?

[英]How to detect a held key in a flash game?

What is the correct way to detect held keys in a flash game? 检测Flash游戏中按住键的正确方法是什么? For example, I want to know that the right arrow is held to move the player. 例如,我想知道按住右箭头可以移动播放器。

Naive code: 天真的代码:

function handleKeyDown(event:KeyboardEvent) {
    held[event.keyCode] = true;
}

function handleKeyUp(event:KeyboardEvent) {
    held[event.keyCode] = false;
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);

The naive code has problems on some computers. 天真的代码在某些计算机上有问题 The KEY_DOWN event is alternating with KEY_UP many times for a held key there. KEY_DOWN事件与KEY_UP交替多次,以保持此处的键。 That makes the key appear to be released in some frames. 这使得该密钥看起来在某些帧中被释放。

An example of the seen events: 可见事件的示例:

[Just holding a single key.]
KEY_DOWN,KEY_UP,KEY_DOWN,KEY_UP,KEY_DOWN,KEY_UP,...

here's a quick fix , with the limitation that it can only work one key at a time 这是一个快速修复方法,其局限性是一次只能使用一个键

var currentKey:uint;

function handleKeyDown(event:KeyboardEvent) {
    held[event.keyCode] = true;

    //make sure the currentKey value only changes when the current key 
    //has been released. The value is set to 0 , 
    //but it should be any value outside the keyboard range
    if( currentKey == 0 )
    {
        currentKey = event.keyCode;

       //limitation: this can only work for one key at a time
       addEventListener(Event.ENTER_FRAME , action );
    }
}

function handleKeyUp(event:KeyboardEvent) {
    held[event.keyCode] = false;

    if( currentKey != 0 )
    {
        //reset
        removeEventListener(Event.ENTER_FRAME , action );
        currentKey = 0;
    }
}

function action(event:Event):void
{
   //your code here
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp);

My workaround is to remember the keys that were seen down at least once in this frame. 我的解决方法是记住在此帧中至少被向下查看一次的键。

function handleKeyDown(event:KeyboardEvent) {
    held[event.keyCode] = true;
    justPressed[event.keyCode] = true;
}

function handleKeyUp(event:KeyboardEvent) {
    held[event.keyCode] = false;
}

// You should clear the array of just pressed keys at the end
// of your ENTER_FRAME listener.
function clearJustPressed() {
    justPressed.length = 0;
}

And I use a function to check if a key was down in this frame: 我使用一个函数来检查此框架中的某个键是否按下:

function pressed(keyCode:int) {
    return held[keyCode] || justPressed[keyCode];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM