ale*_*lex 24 javascript events javascript-events
我有以下问题:我正在尝试编写一个javascript游戏,并且该字符由箭头键控制.
问题是,当按下按键时,在第一次按键和重复按下之间存在短暂的延迟.
此外,当按下"右箭头键"并按住它,然后按下"向上箭头键"时,角色不会移动到右上角,而是停止向右移动并开始向上移动.
这是我正在使用的代码:
<body onLoad="Load()" onKeyDown="Pressed(event)">
Run Code Online (Sandbox Code Playgroud)
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);
}
有没有人有想法?
bob*_*nce 31
如果你想以可控的方式进行密钥重复,你必须自己实现它,因为按键事件的发生取决于操作系统关于密钥重复方式的想法.这意味着可能存在可变的初始延迟和跟随延迟,并且同时按住两个键将导致其中只有一个重复.
您必须记录当前是否按下每个键,并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= {};
};
};
Run Code Online (Sandbox Code Playgroud)
然后:
// 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);
Run Code Online (Sandbox Code Playgroud)
虽然,大多数基于动作的游戏都有一个固定时间的主框架循环,你可以将键上/下操作绑定到.
我已经这样解决了:
var pressl = 0;
var pressu = 0;
var pressr = 0;
var pressd = 0;
函数Down(e){
cxc = e.keyCode;
如果(cxc == 37)
pressl = 1;
如果(cxc == 38)
pressu = 1;
如果(cxc == 39)
Pressr = 1;
如果(cxc == 40)
按下= 1;
// alert(cxc);
}
函数Up(e){
cxc = e.keyCode;
如果(cxc == 37)
pressl = 0;
如果(cxc == 38)
pressu = 0;
如果(cxc == 39)
Pressr = 0;
如果(cxc == 40)
按下= 0;
// alert(cxc);
}
<body onLoad="Load()" onKeyDown="Down(event)" onKeyUp="Up(event)">
| 归档时间: |
|
| 查看次数: |
16399 次 |
| 最近记录: |