如果你想在一个可控的方式键重复,你将不得不自己实现它,按键事件被触发依赖于密钥应该如何重复OS的想法。这意味着可能存在可变的初始延迟和延迟,并且一次按下两个键将只导致其中一个重复。
您必须保存当前每个键是否被按下的记录,并且在键已经关闭时忽略事件。这是因为当发生自动重复时,许多浏览器会触发以及keypress
事件,并且如果您正在重现键重复自己,则需要禁止该事件。
例如:
// Keyboard input with customisable repeat (set to 0 for no key repeat)
//
function KeyboardController(keys, repeat) {
// Lookup of key codes to timer ID, or null for no repeat
//
var timers= {};
// When key is pressed and we don't already think it's pressed, call the
// key action callback and set a timer to generate another one after a delay
//
document.onkeydown= function(event) {
var key= (event || window.event).keyCode;
if (!(key in keys))
return true;
if (!(key in timers)) {
timers[key]= null;
keys[key]();
if (repeat!==0)
timers[key]= setInterval(keys[key], repeat);
}
return false;
};
// Cancel timeout and mark key as released on keyup
//
document.onkeyup= function(event) {
var key= (event || window.event).keyCode;
if (key in timers) {
if (timers[key]!==null)
clearInterval(timers[key]);
delete timers[key];
}
};
// When window is unfocused we may not get key events. To prevent this
// causing a key to 'get stuck down', cancel all held keys
//
window.onblur= function() {
for (key in timers)
if (timers[key]!==null)
clearInterval(timers[key]);
timers= {};
};
};
则:
// Arrow key movement. Repeat key five times a second
//
KeyboardController({
37: function() { Move(-1, 0); },
38: function() { Move(0, -1); },
39: function() { Move(1, 0); },
40: function() { Move(0, 1); }
}, 200);
虽然,大多数基于动作的游戏有一个固定的时间主框架循环,可以配合按键向上/向下处理成。
你的代码不会工作,这是肯定的。我不确定你是否可以测试在JS中同时按下两个键。将等待答案。 – 2010-09-11 15:02:54
好吧,它确实在做事,但并不像预期的那样。我的游戏是一款基于计时器的游戏,等待重复击键并持续1秒就不好。这很令人沮丧。 – alex 2010-09-11 15:08:22
为什么不尝试使用基于闪存的方法。一个透明的闪存swf捕获事件,然后相应地调用JS。 http://www.java2s.com/Code/Flash-Flex-ActionScript/Development/UpLeftSensor.htm – 2010-09-11 15:09:55