Last active
July 1, 2020 04:55
-
-
Save kobus1998/125fc978b5191d580840b99b91bc2f4a to your computer and use it in GitHub Desktop.
Jump animation with requestAnimationFrame
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function update () { | |
// draw methods | |
requestAnimationFrame(update); | |
} | |
update() | |
window.onkeydown = function (e) { | |
if (e.keyCode === 32) { | |
if (!player.isJumping) { | |
player.jump() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Player { | |
constructor () { | |
// ctx, positions, dimensions, isJumping, jumpSpeed, fallSpeed etc... | |
} | |
jumpUp () { | |
this.isJumping = true | |
this.position.y -= this.jumpSpeed | |
this.jumpAnimationUp = requestAnimationFrame(this.jumpUp.bind(this)) // bind jumpUp to request animation frame | |
if (this.position.y < this.ctx.canvas.clientHeight - this.dimension.height - this.jumpHeight) { | |
// player is playerHeight + jumpHeight | |
cancelAnimationFrame(this.jumpAnimationUp) | |
this.jumpDown() | |
} | |
} | |
jumpDown () { | |
this.position.y += this.fallSpeed | |
this.jumpAnimationDown = requestAnimationFrame(this.jumpDown.bind(this)) // bind jumpDown to request animation frame | |
if (this.position.y + this.dimension.height > this.ctx.canvas.clientHeight -1) { | |
// player is bottom of canvas | |
this.isJumping = false | |
cancelAnimationFrame(this.jumpAnimationDown) | |
} | |
} | |
jump () { | |
this.jumpUp() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice