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();
}
}
this
isn't what you expect in the callback. \$\endgroup\$