eldog19950
eldog19950

Reputation: 1

How do I add gravity in a simple game?

So I've been making a simple game and I want gravity, but I don't know where to start. I would like it if I could change the speed that the pieces fall, but whatever works best is fine. Could someone please help me because I have no idea.

Here's my code so far...

Also, this is modified to fit the small preview, so full screening won't work very well.

canvas {
  border: 1px solid #000;
}
<HTML>
<canvas id="canvas" style="position: absolute; left: 0px; top: 0px;"></canvas>
<script>
  var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

  canvas.width = innerWidth-4;
  canvas.height = innerHeight-10;
  canvas.style.backgroundColor = '#87CEEB';
  var x = 150,
    y = 180,
    velY = 0,
    velX = 0,
    speed = 2,
    friction = 0.95,
    keys = [];

  function update() {
    requestAnimationFrame(update);

    if (keys[87]) {
      if (velY > -speed) {
        velY--;
      }
    }
    if (keys[68]) {
      if (velX < speed) {
        velX++;
      }
    }
    if (keys[65]) {
      if (velX > -speed) {
        velX--;
      }
    }
    if (keys[38]) {
      if (velY > -speed) {
        velY--;
      }
    }
    if (keys[39]) {
      if (velX < speed) {
        velX++;
      }
    }
    if (keys[37]) {
      if (velX > -speed) {
        velX--;
      }
    }

    velY *= friction;
    y += velY;
    velX *= friction;
    x += velX;


    if (x >= 1345) {
      x = 1345;
    } else if (x <= 5) {
      x = 5;
    }

    if (y > 180) {
      y = 180;
    } else if (y <= 5) {
      y = 5;
    }

    ctx.clearRect(0, 0, 2000, 1000);
    ctx.beginPath(),
      player = new component(x, y, 'black', 10, 10);
    ctx.fill();
  }

  function component(x, y, color, width, height) {
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    ctx.fillStyle = color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }

  update();

  document.body.addEventListener('keydown', function(e) {
    keys[e.keyCode] = true;
  });
  document.body.addEventListener('keyup', function(e) {
    keys[e.keyCode] = false;
  });
</script>

</html>

Upvotes: 0

Views: 59

Answers (0)

Related Questions