【发布时间】:2021-12-20 08:39:10
【问题描述】:
每次我使用左右箭头键或 A 或 D 移动时,玩家都会加速。我不希望这种情况发生。我希望玩家在按下移动键时以相同的速度移动。我不知道为什么会这样。这是我的代码:
class Player {
constructor(x, y, color, width, height, health, strength, type, speed) {
this.x = x;
this.y = y;
this.color = color;
this.width = width;
this.height = height;
this.health = health;
this.strength = strength;
this.type = type;
this.speed = speed;
}
draw() {
c.beginPath();
c.rect(this.x, this.y, this.width, this.height);
c.fillStyle = this.color;
c.fill();
c.stroke();
}
moveLeft(){
this.x -= this.speed;
}
moveRight(){
this.x += this.speed;
}
moveUp(){
this.y += this.speed;
}
}
var x = canvas.width / 2;
var y = canvas.height / 2;
var left = false;
var up = false;
var right = false;
var left2 = false;
var up2 = false;
var right2 = false;
var pressing;
var player = new Player(x, y, 'red', 30, 30, 100, 30, 'basic', 2);
player.draw();
document.addEventListener('keydown', function(e) {
switch (e.keyCode) {
case 37:
left = true;
setInterval(function pressing(){
if(left2===false && left === true){
player.moveLeft();
}
},10)
break;
case 65:
left2 = true;
setInterval(function pressing(){
if(left===false && left2 === true){
player.moveLeft();
}
},10)
break;
case 39:
right = true;
setInterval(function pressing(){
if(right2===false && right === true){
player.moveRight();
}
},10)
break;
case 68:
right2 = true;
setInterval(function pressing(){
if(right===false && right2 === true){
player.moveRight();
}
},10)
break;
}
});
document.addEventListener("keyup", event => {
clearInterval(pressing);
if (event.keyCode === 37) {
left = false;
}
if (event.keyCode === 65) {
left2 = false;
}
if (event.keyCode === 39) {
right = false;
}
if (event.keyCode === 68) {
right2 = false;
}
});
我遵循了许多教程,但找不到其他简单的方法来移动我的播放器。有没有人有其他的移动策略或知道为什么这不起作用?
【问题讨论】:
-
您绝不会清除这些间隔,因此每次按下按钮都会设置一个新的间隔,从而使整个过程变得越来越快。要让游戏运行,您可能应该有一个“事件循环”,通常使用
requestAnimationFrame,在该循环中您检查按钮的状态并确定要做什么。
标签: javascript html canvas html5-canvas