fix your timestep javascript

var t = 0;
var dt = 0.01;

var currentTime;
var accumulator = 0;

var previousState = { x: 100, v: 0 };
var currentState = { x: 100, v: 0 };

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

// start animation loop
requestAnimationFrame(animate);

function animate(newTime){
  requestAnimationFrame(animate);

  if (currentTime) {
    var frameTime = newTime - currentTime;
    if ( frameTime > 250 )
        frameTime = 250;
    accumulator += frameTime;

    while ( accumulator >= dt )
    {
        previousState = currentState;
        currentState = integrate( currentState, t, dt );
        t += dt;
        accumulator -= dt;
    }

    var alpha = accumulator / dt;
    var interpolatedPosition = currentState.x * alpha + previousState.x * (1 - alpha);

    render( interpolatedPosition );
  }

  currentTime = newTime;
}

// Move simulation forward
function integrate(state, time, fixedDeltaTime){
  var fixedDeltaTimeSeconds = fixedDeltaTime / 1000;
  var f = (200 - state.x) * 3;
  var v = state.v + f * fixedDeltaTimeSeconds;
  var x = state.x + v * fixedDeltaTimeSeconds;
  return { x: x, v: v };
}

// Render the scene
function render(position){
  // Clear
  ctx.fillStyle = 'white';
  ctx.fillRect(0,0,canvas.width,canvas.height);

  // Draw circle
  ctx.fillStyle = 'black';
  ctx.beginPath();
  ctx.arc(position,100,50,0,2*Math.PI);
  ctx.closePath();
  ctx.fill();
}

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source