Search code examples
javascripthtmlcanvas

having problems with simulating gravity in canvas


I'm having problems with my gravity in my canvas.

The code I provided below. I tried to calculate the position in different ways, expected it to fall like usual with acceleration, except it just floats in the air.

var canvas = document.getElementById("myCanvas");
var m = canvas.getContext('2d');
var gravity = 9.8; //as in 9.8m/s²
var height = 0;
var v = Math.sqrt((2 * height) / gravity);

function update() {
  m.clearRect(0, 0, canvas.width, canvas.height);
  m.fillRect(0, height, 10, 10);
  height += v;
  return v;
  requestAnimationFrame(update);
}

requestAnimationFrame(update);
<canvas id="myCanvas" width="300" height="300"></canvas>


Solution

  • Returning v stops the function from requesting the next animation frame. Also, the values of height and v always remain zero.

    I assigned height an initial value greater than zero, declared v within the function, and removed the return.

    const canvas = document.getElementById("myCanvas");
    const m = canvas.getContext('2d');
    const gravity = 9.8; //as in 9.8m/s²
    let height = 1;
    
    function update() {
      m.clearRect(0, 0, canvas.width, canvas.height);
      m.fillRect(0, height, 10, 10);
      let v = Math.sqrt((2 * height) / gravity);
      height += v;
      requestAnimationFrame(update);
    }
    
    requestAnimationFrame(update);
    <canvas id="myCanvas" width="300" height="300"></canvas>