永远循环并提供增量时间 [英] Loop forever and provide delta time

查看:150
本文介绍了永远循环并提供增量时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个HTML5游戏开发Javascript框架,我想为用户提供最后一个刻度和当前刻度之间的时间差。

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

我试过,使用date.getTime();计算增量时间,但Firefox说脚本崩溃了。显然,无限循环会崩溃。我有什么建议可以解决这个问题吗?

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?

我想要一个无限循环,可以用中断。我也希望传递delta时间,但我知道该怎么做。

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.

推荐答案

只需保持变量与时间的关系上次更新,并以 tick 本身计算经过时间/增量时间。

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

这是一个JSBin,虽然我不认为它真的需要...... http://jsbin.com/okimam/10

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

编辑
我必须指出 setInterval(tick,0)并不一定意味着 tick 将立即被调用,两次调用之间的间隔为0ms。这取决于浏览器。

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.

这篇关于永远循环并提供增量时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆