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

我投票作为题外话,因为它是要求找到一些示例源代码 – rlemon

+0

'then'在一个层次较高的范围,无疑宣布的声明,关闭了这个问题 - 最有可能 - 主关闭。表达式函数变量'main'用于(无疑)更新调用之间的时间间隔并呈现相应的帧;将'then'更新为'now',使其为随后的调用相同表达式(main)的'requestAnimationFrame'做好准备,以进行新的更新和delta计算。 –

我将尝试解释我从教程中的代码中理解的内容。
游戏通常以固定的帧率运行,如每秒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()。

阅读开始游戏人数10:

// Let's play this game! 
var then = Date.now(); 
reset(); 
main(); 

下面的描述还:

“几乎在那里,这是最后一个代码片段!首先,我们设置我们的时间戳(然后是变量),然后我们调用重置来开始一个新的游戏/关卡。“

+0

请在提问前仔细阅读 – yass

+0

干杯!完全错过了它在调用函数之前声明的内容。 – Melvin

没有读得不够好。找到了声明。谢谢!