2010-09-12 52 views
1

什么是在Flash游戏中检测持有按键的正确方法?例如,我想知道右边的箭头是为了移动玩家。如何检测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,... 

回答

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]; 
} 
+1

justPressed.length = 0;而不是justPressed = []。为什么当你可以重新使用旧的时候,为什么每一帧都要创建新的数组 – alxx 2010-09-13 06:55:28

+0

@alxx谢谢。我更新了代码。 – 2010-09-13 10:04:37

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

对不起,误会。交替KEY_UP事件的问题仍未解决。如果交替KEY_UP被视为最后一个事件,则currentKey将为0.这将导致运动暂停。 – 2010-09-12 19:46:46

+0

好的,但一旦再次按下该键,动作就会开始。我认为当钥匙被释放时,你需要一种停止动作的方式。这个想法是涵盖所有无意的关键事件。另一种方法是通过按另一个键来停止动作。 – PatrickS 2010-09-13 03:14:24