1
\$\begingroup\$

I am trying to make a jump function.

I am making a game in html5 canvas with Javascript. I have gotten the player to move. When making the jump function I decided to use a timeout to reverse the coordinates back to the original after a set time.

The error is after the character moves up he does not return to the original position the character just stays there, and then upon clicking the jump (arrow key) again the player goes the other way e.g (down).

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();
  }
}
\$\endgroup\$
1
  • \$\begingroup\$ Check your console for errors. this isn't what you expect in the callback. \$\endgroup\$
    – tkausl
    Commented Jun 24, 2019 at 7:51

1 Answer 1

0
\$\begingroup\$

Your setTimeout is not bound to context of class you need to either bind callback

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

or use arrow function

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .