javascript - 使用超时来做跳转功能

标签 javascript html5-canvas

我正在 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/

相关文章:

javascript - 使用javascript更改图像部分的颜色

javascript - $(.class) 仅针对该类名的第一个标签执行

javascript - 我的 circle-divs 不工作。为什么?

javascript - 如何在 React 中渲染 `HTMLCanvasElement`?

javascript - 为什么我不能在我的 HTML5 canvas 中绘制一个矩形?

javascript - 如何从 jspdf 页面中删除顶部/底部边框?

JavaScript:如何知道与共享 worker 的连接是否仍然存在?

javascript - 我怎样才能最大限度地兼容旧浏览器?

javascript - 如何在不使用 ng-transclude 的情况下为 angularjs 编写替换 dom 元素的指令?

html - 将 HTML Canvas 缩放到浏览器窗口大小,但不缩放 Canvas 内的元素