I have a function in class Player called jump(), which should move the player object up by 15, unless it's 20 from the top of the canvas, in which case it drops by 20. Then it calls the function fall(), after a brief wait, which drops the position of the player by 15 - theoretically resulting in the player being put back to where they were after falL() executes. However, the problem is that if you spam the jump button or hold it down enough, when the fall()s come through, it drops the player far below where it started. Is this because of the roof collision check?
function fall() {
player.y += 15
}
(within class Player:)
jump() {
this.y -= 15;
if (this.y <= 20){ // check roof
this.y += 20
}
setTimeout(fall,550);
}
How can I make it so the user can hold the jump button, and not end up with a y lower than their starting y?
Sounds like you might want to just only set the timeout to fall if the player actually jumps in the first place.
jump() {
if (this.y <= 5){
// roof
this.y += 5
} else {
// jump
this.y -= 15;
setTimeout(fall, 550);
}
}
I don't know what your app is like, but depending on the setup, a more elegant approach might be to, during the game loop, check if there's anything under the player (like the floor, or some other platform), and if there isn't, change their y appropriately, so that the falling action is more consistent and not tied to jump.