【发布时间】:2011-06-16 19:38:19
【问题描述】:
目前我正在开发一款名为“隧道 2”的小型 js/canvas 游戏(我很确定有一个众所周知的旧版本,但我不知道)。你可以try the game here。另外,我会推荐 chrome。
所以,我在 google chrome 中开发,它工作正常,即使在我蹩脚的旧机器上也是如此。我得到大约 30 fps。在我同事的笔记本上,它产生 >100fps。到目前为止,一切都很好。 safari 似乎也很好用。
接下来我在 firefox 4 beta 10 上尝试了它......我只能获得 ~10 fps。但肯定 ff4 并没有那么慢,对吧?
我开始调查。这是我的主循环:
// starts the game loop
this.run = function () {
this.draw();
var
t = this,
timeLastTurn,
timeThisTurn = (new Date()).getTime()-1;
var loop = function () {
timeLastTurn = timeThisTurn;
timeThisTurn = (new Date()).getTime();
// dt is the time difference between this turn and the last turn
var dt = timeThisTurn - timeLastTurn;
// player movement etc
t.turn(dt);
// draw game state
var res = t.draw();
// if there's no collision, game over
if (!res.collision)
t.setState(2);
// actually, there's a browser dependent minimum timeout that
// may vary. but even if it's more than 10ms - we don't care.
// game should run at the same speed (though not as smooth)
if (gameState == 1)
timer = window.setTimeout(loop, 5);
// just debug output
debug = dt;
}
// start the main loop
loop();
}
我观察到的:
不出所料,this.draw(); 是迄今为止最昂贵的功能,但它只需要几毫秒(实际上大约 5),在 chrome ... 和 firefox 上。远不及> 100毫秒,这将需要微不足道的10fps!整个loop() 调用也不会花费太多时间,在 Firefox 上只需不到 10 毫秒!
如果您调查dt,就会发现差异。它应该在 time-loop()-takes+5ms 超时(或浏览器最小超时值)左右。
但在 ff4 上,该值更接近 180 毫秒,即下一个超时事件在 170 毫秒而不是 5 毫秒内触发!如果你玩的时间再长一点,单帧会达到约 800 毫秒(肯定是 gc),然后又回到 180 毫秒。
有人知道罪魁祸首是什么吗?
是 GC 的罪魁祸首吗?一方面,我不认为我创建了太多短暂的变量,嘿,每次 150 毫秒!?但当然可以。有没有简单的方法来检查这个? chrome profiler 记录 gc 时间(大约 0.10%),但 firebug profiler 没有。
也很有趣:游戏在启用 firebug 的情况下运行得更快(~5fps)。
添加。信息:使用 setInterval 而不是 setTimeout 不应该也不会改变任何东西。
【问题讨论】:
-
不错的令人上瘾的游戏 - 虽然在玩了 98.1 秒并回到 stackoverflow 之后,我觉得我的眼睛被蒙蔽了,很痛......
-
你试过FF4中的萤火虫探查器吗?
-
@Schnalle firefox 错误:
ctx.arc(75,75,50,0,Math.PI*2,true);见第 270 行。.arc 需要 6 个参数而不是 5 个。 -
@shadi:谢谢!是的,配色方案很疯狂。我会改变它! @raynos:是的,我试过了,但我什么也没找到。感谢 ctx.arc 错误(尽管没有它也能正常工作)。 @fazo:然后在 chrome 中播放,你会得到超过 100fps :)
-
实际上 arc 的第 6 个参数是可选的,默认为 false(顺时针) - 检查参考 whatwg.org/specs/web-apps/current-work/multipage/…
标签: javascript firefox html canvas