我尝试重新创建Pong game by Atari,目前我遇到了多个关键处理程序。
我对当前解决方案的问题是,浏览器似乎无法处理多个键输入,这就是为什么我无法顺利移动两个paddleys。
我处理键输入的方式如下所示:
document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);
function keyDownHandler(e) {
if(e.keyCode == 40) {
DownArrowPressed = true;
console.log('down pressed')
}
else if(e.keyCode == 38) {
UpArrowPressed = true;
console.log('up pressed')
}
else if(e.keyCode == 68) {
Dpressed = true;
console.log('d pressed')
}
else if(e.keyCode == 67) {
Cpressed = true;
console.log('c pressed')
}
}
function keyUpHandler(e) {
if(e.keyCode == 40) {
DownArrowPressed = false;
}
else if(e.keyCode == 38) {
UpArrowPressed = false;
}
else if(e.keyCode == 68) {
Dpressed = false;
}
else if(e.keyCode == 67) {
Cpressed = false;
}
}
P.S。我一直在浏览stackoverflow并找到了这个帖子:javascript multiple keys pressed at once
更新:使用上述线程的代码:
> document.addEventListener("Down", onkeydown, false);
document.addEventListener("up", onkeyup, false);
var map = []; // Or you could call it "key"
onkeydown = onkeyup = function(e){
e = e || event; // to deal with IE
map[e.keyCode] = e.type == 'keydown';
// D + up arrow
if (map[68] && map["38"]) {
Dpressed = true;
UpArrowPressed = true;
}
// D + down arrow
else if (map[68] && map["40"]) {
Dpressed = true;
DownArrowPressed = true;
}
// C + up arrow
else if (map[67] && map[38]) {
Cpressed = true;
UpArrowPressed = true;
}
// C + down arrow
else if (map[67] && map[40]) {
Cpressed = true;
DownArrowPressed = true;
}
// Down arrow
else if(map[40]) {
DownArrowPressed = true;
}
// Up arrow
else if(map[38]) {
UpArrowPressed = true;
}
// D
else if(map[68]) {
Dpressed = true;
}
// C
else if( map[67]) {
Cpressed = true;
}
}
使用此代码,拨片不会平滑移动并卡在画布的底部。我觉得我的实施中存在错误,但我无法看到它们-_-