gpt4 book ai didi

javascript - 消除 Javascript 中的按键延迟

转载 作者:行者123 更新时间:2023-12-03 02:03:06 25 4
gpt4 key购买 nike

我有以下问题:我正在尝试编写一个 Javascript 游戏,并且 Angular 色由箭头键控制。
问题是,当一个人按住按键时,在触发第一个按键和重复的按键之间存在短暂的延迟。
另外,当按下“向右箭头键”并保持按下状态,然后按下“向上箭头键”时, Angular 色不会移动到右上角,而是停止向右方向移动并开始向上移动。
这是我正在使用的代码:

<body onLoad="Load()" onKeyDown="Pressed(event)">
function Pressed(e) {         cxc = e.keyCode;        if(cxc == 37)            Move(-1,0);        if(cxc == 38)            Move(0,-1);        if(cxc == 39)            Move(1,0);        if(cxc == 40)            Move(0,1);    }

有人有想法吗?

最佳答案

如果您希望以可控的方式重复按键,则必须自己实现,因为按键事件的触发取决于操作系统对按键应如何重复的想法。这意味着可能存在可变的初始延迟和后续延迟,并且同时按住两个键只会导致其中一个键重复。

您必须记录当前是否按下每个键,并在按键已按下时忽略 keydown 事件。这是因为许多浏览器在发生自动重复时会触发 keydown 以及 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);

尽管如此,大多数基于 Action 的游戏都有一个固定时间的主帧循环,您可以将向上/向下按键处理绑定(bind)到其中。

关于javascript - 消除 Javascript 中的按键延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3691461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com