Never let your physics simulation depend on something as unreliable and capricious as the machine’s framerate.
When I was building Electric Field Hockey I used window.requestAnimationFrame
to control the time-step for all the physics calculations.
Simulation Tick Function
Simulation.prototype.tick = function(frame) {
var ts = frame.timeDiff / 1000;
var puck = this.puck;
var force = puck.charge.calcForceFrom( this.charges );
var newPosition = EFH.Physics.calcPosition(puck.charge,
puck.velocity, force, ts);
puck.velocity = EFH.Physics.calcVelocity(puck.velocity,
force, ts);
puck.moveTo(newPosition.x, newPosition.y);
};
var init = function() {
self.anim = new Kinetci.Animation(function(frame) {
self.tick( frame );
});
};
It’s easy and straight forward: every time the browser wanted a new frame, we can calculate the forces, apply them to the objects, and figure out the new positions.
But it’s also simplistic.