Skip to content
This repository was archived by the owner on Jan 13, 2023. It is now read-only.

Latest commit

 

History

History
56 lines (56 loc) · 1.73 KB

File metadata and controls

56 lines (56 loc) · 1.73 KB

< Previous     Next >


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:
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;
  }
}

Hit the Bottom

To prevent the red square from falling outside of the canvas, stop the falling when it hits the bottom of the game area:
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;
  }
}

Accelerate

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:
<script>
function accelerate(n) {
  myGamePiece.gravity = n;
}
</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>