THE WORLD'S LARGEST WEB DEVELOPER SITE

Game Gravity


Some games have forces that pulls the game component in one direction, like gravity pulls objects to the ground.




Gravity

To add this functionality to our component constructor, first add a gravity property, which sets the current gravity. Then add a gravitySpeed property, which increases everytime we update the frame:

Example

function component(width, height, color, x, y, type) {
  this.type = type;
  this.width = width;
  this.height = height;
  this.x = x;
  this.y = y;
  this.speedX = 0;
  this.speedY = 0;
  this.gravity = 0.05;
  this.gravitySpeed = 0;
 
this.update = function() {
    ctx = myGameArea.context;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
  }
}
Try it Yourself »


Hit the Bottom

To prevent the red square from falling forever, stop the falling when it hits the bottom of the game area:

Example

  this.newPos = function() {
    this.gravitySpeed += this.gravity;
    this.x += this.speedX;
    this.y += this.speedY + this.gravitySpeed;
    this.hitBottom();
  }
  this.hitBottom = function() {
    var rockbottom = myGameArea.canvas.height - this.height;
    if (this.y > rockbottom) {
      this.y = rockbottom;
    }
  }

Try it Yourself »

Accelerate Up

In a game, when you have a force that pulls you down, you should have a method to force the component to accelerate up.

Trigger a function when someone clicks a button, and make the red square fly up in the air:

Example

<script>
function accelerate(n) {
  myGamePiece.gravity = n;
}
</script>

<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>
Try it Yourself »

A Game

Make a game based on what we have learned so far: