Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/461.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用超时生成跳转函数_Javascript_Html5 Canvas - Fatal编程技术网

Javascript 使用超时生成跳转函数

Javascript 使用超时生成跳转函数,javascript,html5-canvas,Javascript,Html5 Canvas,我正在用html5画布制作一个游戏。我已经让球员得到了更多。在做跳转函数时,我决定使用一个时间,在设定的时间后,将坐标反转回原始坐标 错误是什么都没有发生,再次点击后,玩家会走另一条路e.gdown class Character{ constructor(){ this.x = 50; this.y = 400; this.posX=0; this.posY=0; this.width; this.height; this.hitPoints=1; this.directionFace="ri

我正在用html5画布制作一个游戏。我已经让球员得到了更多。在做跳转函数时,我决定使用一个时间,在设定的时间后,将坐标反转回原始坐标

错误是什么都没有发生,再次点击后,玩家会走另一条路e.gdown

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以50ms设置,并等待键盘输入。

以下函数有它自己的设置,它不会是您的字符类的实例

请尝试以下代码,胖箭头函数没有自己的此上下文,将捕获并保留父上下文

setTimeout(() => {
            this.posY = this.jumpHeight;          
            this.jumping = false;
        }, 500);

您正在移动方法的开始处设置x和y。在对posX和posY进行任何更改后,尝试将它们移动到末尾。同时,实施Ivan的改变


您还需要在方法开始时重置posX和posY。否则,当按下任何键时,字符将继续向上或侧向移动。

x和y被设置,因为我需要使字符显示在屏幕上的正确位置,除非我在这方面有错误。但是,这些x和y仅在按下键时才被更改。因此,您需要在按键if语句之后设置它们。
setTimeout(() => {
            this.posY = this.jumpHeight;          
            this.jumping = false;
        }, 500);