showing results for - "fix your timestep javascript"
Paul
03 Jun 2018
1var t = 0;
2var dt = 0.01;
3
4var currentTime;
5var accumulator = 0;
6
7var previousState = { x: 100, v: 0 };
8var currentState = { x: 100, v: 0 };
9
10var canvas = document.getElementById("myCanvas");
11var ctx = canvas.getContext("2d");
12
13// start animation loop
14requestAnimationFrame(animate);
15
16function animate(newTime){
17  requestAnimationFrame(animate);
18
19  if (currentTime) {
20    var frameTime = newTime - currentTime;
21    if ( frameTime > 250 )
22        frameTime = 250;
23    accumulator += frameTime;
24
25    while ( accumulator >= dt )
26    {
27        previousState = currentState;
28        currentState = integrate( currentState, t, dt );
29        t += dt;
30        accumulator -= dt;
31    }
32
33    var alpha = accumulator / dt;
34    var interpolatedPosition = currentState.x * alpha + previousState.x * (1 - alpha);
35
36    render( interpolatedPosition );
37  }
38
39  currentTime = newTime;
40}
41
42// Move simulation forward
43function integrate(state, time, fixedDeltaTime){
44  var fixedDeltaTimeSeconds = fixedDeltaTime / 1000;
45  var f = (200 - state.x) * 3;
46  var v = state.v + f * fixedDeltaTimeSeconds;
47  var x = state.x + v * fixedDeltaTimeSeconds;
48  return { x: x, v: v };
49}
50
51// Render the scene
52function render(position){
53  // Clear
54  ctx.fillStyle = 'white';
55  ctx.fillRect(0,0,canvas.width,canvas.height);
56
57  // Draw circle
58  ctx.fillStyle = 'black';
59  ctx.beginPath();
60  ctx.arc(position,100,50,0,2*Math.PI);
61  ctx.closePath();
62  ctx.fill();
63}