我正在 html5 canvas 中制作游戏。我已经让玩家获得更多。在制作跳跃功能时,我决定使用时间在设定的时间后将坐标反转回原来的位置。
错误是没有发生任何事情,再次单击它时,玩家会转向另一个方向,例如(向下);
class Character{
constructor(){
this.x = 50;
this.y = 400;
this.posX=0;
this.posY=0;
this.width;
this.height;
this.hitPoints=1;
this.directionFace="right";
this.jump = false;
this.jumpHeight = 23;
}
move(e){
this.x += this.posX;
this.y += this.posY;
if(e.keyCode == 37){
console.log('left');
this.posX -= 10;
}
else if (e.keyCode ==38){
console.log("UP");
if (!this.jumping) {
this.posY -= this.jumpHeight;
this.jumping = true;
setTimeout(function(){
this.posY = this.jumpHeight;
this.jumping = false;
}, 500);
}
}
else if (e.keyCode == 39){
console.log("right");
this.posX+=10;
}
e.preventDefault();
}
我有另一个类设置,它是使用 setInterval 设置为 50 毫秒并等待键盘输入。
最佳答案
以下函数有自己的 this
,它不会是 Character
类的实例。
setTimeout(function(){
this.posY = this.jumpHeight;
this.jumping = false;
}, 500);
尝试以下代码,粗箭头函数没有自己的 this
上下文,并将捕获并保留父上下文。
setTimeout(() => {
this.posY = this.jumpHeight;
this.jumping = false;
}, 500);
关于javascript - 使用超时来做跳转功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56727408/