Skip to content

Instantly share code, notes, and snippets.

@tmcw
Created March 6, 2014 14:42
Show Gist options
  • Save tmcw/9391224 to your computer and use it in GitHub Desktop.
Save tmcw/9391224 to your computer and use it in GitHub Desktop.

Gravity!

Okay, a function for gravity. let's look at it piece by piece then throw it in:

update: function() {

  // this is where the ground is on your level. adjust to fit.
  var ground = 300;

  // if this has no velocity yet, set it to zero
  if (this.velocity == undefined) {
    this.velocity = 0;
  }
  // if you're on the ground and pressing the up arrow, jump
  if (this.c.inputter.isDown(this.c.inputter.UP_ARROW) && this.center.y == ground) {
    this.velocity += 7;
  }

  // this actually moves the character upwards!
  this.center.y -= this.velocity;

  // if we're in the air, gravity pulls us downwards! adjust 0.2 to other
  // numbers to change gravity
  if (this.center.y < ground) {
      this.velocity -= 0.2;
  }

  // if we've hit the ground, let's stop moving.
  if (this.center.y >= ground) {
    this.velocity = 0;
    this.center.y = ground;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment