Loop forever and provide delta time

半腔热情 提交于 2019-12-05 02:55:40

问题


I'm writing an HTML5 Game Development Javascript framework and I want to provide the user the difference in time between the last tick and the current one.

setInterval(tick, 16.6666666);

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

That's what I have, but I want to have:

while (true) {
  /* Calculate delta time */

  tick(dt);
}

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

I tried that, using date.getTime(); to calculate delta time, but Firefox said the script crashed. Obviously, an infinite loop will crash. Got any suggestions for how I can go about this?

I want an infinite loop, that can be stopped with break. I want to pass delta time too, but that I know how to do.


回答1:


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.




回答2:


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)



回答3:


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.




回答4:


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);


来源:https://stackoverflow.com/questions/13996267/loop-forever-and-provide-delta-time

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