date.now()'then'在这里做什么? - Javascript
问题描述:
我已经使用这个教程来帮助我为我的作业写一个简单的JS游戏。然而,我现在正在研究gameloop,我不知道这个特定功能是如何工作的。date.now()'then'在这里做什么? - Javascript
这是本教程的URL。的代码,你要查找的块是在8 “的游戏主循环” http://www.lostdecadegames.com/how-to-make-a-simple-html5-canvas-game/
//Gameloop
var main = function() {
//var with timestamp
var now = Date.now();
//where does 'then' come from? I never declared it.
var delta = now - then;
//next up it just calls another func and provides parameter delta divided by 1000 which is the amount of miliseconds in a second
update(delta/1000);
//and it calls my render function
render();
//then it sets then back to Date.now()
then = now;
//No idea what this line does. still looking into it
requestAnimationFrame(main);
};
答
我将尝试解释我从教程中的代码中理解的内容。
游戏通常以固定的帧率运行,如每秒60帧(FPS)。
在教程中,情况并非如此。 而不是固定的帧率和在update
函数中移动固定距离的字符,您有一个delta变量用于计算距离。
hero.y -= hero.speed * modifier; // modifier is (delta/1000)
像其他的答案说,then
在开始设置,在主函数的外部范围。
// Let's play this game!
var then = Date.now();
reset();
main();
我会补充说教程有点旧(2011),有些细节可以改进。例如,您可以使用performance.now()而不是如lighthouse所报告的Date.now()。
答
没有读得不够好。找到了声明。谢谢!
我投票作为题外话,因为它是要求找到一些示例源代码 – rlemon
'then'在一个层次较高的范围,无疑宣布的声明,关闭了这个问题 - 最有可能 - 主关闭。表达式函数变量'main'用于(无疑)更新调用之间的时间间隔并呈现相应的帧;将'then'更新为'now',使其为随后的调用相同表达式(main)的'requestAnimationFrame'做好准备,以进行新的更新和delta计算。 –