如何在Flash游戏中检测保持键?

时间:2010-09-12 13:44:06

标签: flash actionscript-3 keyboard

在Flash游戏中检测保持键的正确方法是什么? 例如,我想知道右箭头是为了移动玩家。

天真的代码:

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);

某些计算机上的天真代码存在问题。 对于持有的密钥,KEY_DOWN事件与KEY_UP交替多次。 这使得密钥似乎在某些框架中被释放。

所见事件的一个例子:

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

2 个答案:

答案 0 :(得分:0)

这是一个快速修复,其限制是它一次只能处理一个键

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);

答案 1 :(得分:0)

我的解决方法是记住那些密钥 在这个框架中至少看过一次。

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;
}

我使用一个函数来检查该帧中的键是否已关闭:

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