Loop forever and provide delta time

若如初见. 提交于 2019-12-03 20:44:56

Just maintain a variable with the time of the last update, and calculate the elapsed time/delta time in tick itself.

var lastUpdate = Date.now();
var myInterval = setInterval(tick, 0);

function tick() {
    var now = Date.now();
    var dt = now - lastUpdate;
    lastUpdate = now;

    update(dt);
    render(dt);
}

Here's a JSBin, though I don't think it's really needed... http://jsbin.com/okimam/10

EDIT: I must point out that setInterval(tick, 0) does not necessarily mean that tick will be called immediately, with an interval of '0ms' between two calls. It depends on the browser.

This is what I use:

var lastTick = performance.now()

function tick(nowish) {
  var delta = nowish - lastTick
  lastTick = nowish

  update(delta)
  render(delta)

  window.requestAnimationFrame(tick)
}

window.requestAnimationFrame(tick)

Would like to give my two cents. Usually I use this deltatime method in my games:

const perfectFrameTime = 1000 / 60;
let deltaTime = 0;
let lastTimestamp = 0;

function start() {
    requestAnimationFrame(update);
}

function update(timestamp) {
    requestAnimationFrame(update);
    deltaTime = (timestamp - lastTimestamp) / perfectFrameTime;
    lastTimestamp = timestamp;

    // YOUR FRAME CODE HERE!

}

start();

This ensure you will have perfect deltatime (as like Unity deltaTime) so you can scale your times to frame time.

Are you over thinking it?

var myInterval = window.setInterval(calculateForDeltaHere , 20);

function calculateForDeltaHere () {
    /* Calculate delta time */
    dt = Math.random();
    tick(dt);
}

function tick() {  
  update();
  draw();
}

And when you want to stop the interval

window.clearInterval(myInterval);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!