我正在学习 JavaScript,并且正在尝试编写一个小游戏。 我希望我的游戏中的某些东西在我按住某个键时始终如一地移动。 到目前为止,这是我想出的:
document.onkeydown = onKeyDownListener;
function onKeyDownListener(evt) {
var keyCode = evt.which || evt.keyCode;
if(keyCode == 37) {
move();
}
}
我的问题是,当我按下键时,移动会被调用一次,然后会有一个暂停,然后暂停移动会按照我的意图重复调用。它去 像这样:m ......mmmmmmmmm 当'm'代表移动和'。是暂停。 有没有办法摆脱暂停?
这是发生的情况的 GIF:
最佳答案
我很确定您遇到了这个问题,因为您没有依赖游戏循环来运行您的游戏。如果你是,你就不会遇到这个问题,因为每个间隔的游戏循环都会检查是否按下了键。您的网络应用只会在每次按键时使用react。
我强烈建议您阅读本教程:
W3 HTML 游戏 - 游戏 Controller
https://www.w3schools.com/graphics/game_movement.asp
阅读“键盘作为 Controller ”部分。 “setInterval”方法在此示例中引入游戏循环。
我用它作为自己编写游戏代码的引用。
这是 W3 教程中的代码。它还继续教授碰撞检测。
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 480;
this.canvas.height = 270;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function (e) {
myGameArea.keys = (myGameArea.keys || []);
myGameArea.keys[e.keyCode] = true;
})
window.addEventListener('keyup', function (e) {
myGameArea.keys[e.keyCode] = false;
})
},
clear : function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.speedX = 0;
myGamePiece.speedY = 0;
if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -1; }
if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 1; }
if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -1; }
if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 1; }
myGamePiece.newPos();
myGamePiece.update();
}
关于javascript - JS 按住一个键有延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49394068/