当我按下任何箭头或使用 WSAD 时,在 keydown 事件的第一次“激活”之后,到下一个事件会有轻微的延迟,但之后就正常了。示例:当您按住箭头时,您移动 1px,稍等片刻,然后开始定期正常移动 1px。
我的代码:
//========== KEY LOGGING ==========
var pressedKeys = [];
//declare as globals coz of debug
var x;
var y;
var x2;
var y2;
function checkMove(checkX, checkY, cSize, cSpeed, direction) {
x = checkX - cSpeed;
y = checkY - cSpeed;
x2 = checkX + cSize + cSpeed;
y2 = checkY + cSize + cSpeed;
switch (direction) {
case 1:
// left
if (x > 0) {
return checkX - cSpeed;
} else {
return 0;
}
break;
case 2:
// up
if (y > 0) {
return checkY - cSpeed;
} else {
return 0;
}
break;
case 3:
// right
if (x2 < width) {
return checkX + cSpeed;
} else {
return width - cSize;
}
break;
case 4:
// down
if (y2 < height) {
return checkY + cSpeed;
} else {
return height - cSize;
}
break;
default:
return; // exit this handler for other keys
}
}
// == KEYDOWN ==
$(document.body).keydown(function (e) {
pressedKeys[e.which] = true;
$.each(playerList, function (i, currentPlayer) {
//player 1
if (currentPlayer.id == 0) {
//left
if (pressedKeys[37] == true) {
currentPlayer.x = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 1)
}
//up
if (pressedKeys[38] == true) {
currentPlayer.y = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 2)
}
//right
if (pressedKeys[39] == true) {
currentPlayer.x = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 3)
}
//down
if (pressedKeys[40] == true) {
currentPlayer.y = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 4)
}
}
//player 2
else if (currentPlayer.id == 1) {
//left
if (pressedKeys[65] == true) {
currentPlayer.x = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 1)
}
//up
if (pressedKeys[87] == true) {
currentPlayer.y = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 2)
}
//right
if (pressedKeys[68] == true) {
currentPlayer.x = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 3)
}
//down
if (pressedKeys[83] == true) {
currentPlayer.y = checkMove(currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, 4)
}
}
//addplayer
if (pressedKeys[80] == true && id < 5) {
addPlayer("red", size, width / 2, height / 2);
}
//+
if (pressedKeys[107] == true) {
currentPlayer.speed += 1;
}
//-
if (pressedKeys[109] == true && currentPlayer.speed > 1) {
currentPlayer.speed -= 1;
}
});
});
// == KEYUP ==
$(document.body).keyup(function (e) {
delete pressedKeys[e.which];
});