Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active July 1, 2020 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kobus1998/125fc978b5191d580840b99b91bc2f4a to your computer and use it in GitHub Desktop.
Save kobus1998/125fc978b5191d580840b99b91bc2f4a to your computer and use it in GitHub Desktop.
Jump animation with requestAnimationFrame
function update () {
// draw methods
requestAnimationFrame(update);
}
update()
window.onkeydown = function (e) {
if (e.keyCode === 32) {
if (!player.isJumping) {
player.jump()
}
}
}
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()
}
}
@agmitron
Copy link

agmitron commented Jul 1, 2020

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment