date.now() 'then' 在这里做什么? - Javascript
What does date.now() 'then' does here? - Javascript
我使用本教程帮助我为学校作业编写了一个简单的 JS 游戏。但是我现在正在查看游戏循环,但我不知道这个特定功能是如何工作的。
这是教程的URL。您要查找的代码块位于 8 "The main game loop"
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);
};
阅读开始游戏编号 10:
// Let's play this game!
var then = Date.now();
reset();
main();
下面的描述也是:
"Almost there, this is the last code snippet! First we we set our timestamp (with the variable then) to seed it. Then we call reset to start a new game/level."
我将尝试解释我从教程中的代码中理解的内容。
游戏通常以固定的帧速率运行,例如每秒 60 帧 (FPS)。
在本教程中,情况并非如此。
在 update
函数中,您没有使用固定的帧率并以固定的距离移动角色,而是使用了一个增量变量来计算距离。
hero.y -= hero.speed * modifier; // modifier is (delta / 1000)
就像其他答案所说的那样,then
设置在开头,在 main 函数的外部范围内。
// Let's play this game!
var then = Date.now();
reset();
main();
我会补充一点,教程有点旧(2011),一些细节可以改进。例如,您可以使用 performance.now() instead of Date.now() as reported by lighthouse.
我使用本教程帮助我为学校作业编写了一个简单的 JS 游戏。但是我现在正在查看游戏循环,但我不知道这个特定功能是如何工作的。
这是教程的URL。您要查找的代码块位于 8 "The main game loop" 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);
};
阅读开始游戏编号 10:
// Let's play this game!
var then = Date.now();
reset();
main();
下面的描述也是:
"Almost there, this is the last code snippet! First we we set our timestamp (with the variable then) to seed it. Then we call reset to start a new game/level."
我将尝试解释我从教程中的代码中理解的内容。
游戏通常以固定的帧速率运行,例如每秒 60 帧 (FPS)。
在本教程中,情况并非如此。
在 update
函数中,您没有使用固定的帧率并以固定的距离移动角色,而是使用了一个增量变量来计算距离。
hero.y -= hero.speed * modifier; // modifier is (delta / 1000)
就像其他答案所说的那样,then
设置在开头,在 main 函数的外部范围内。
// Let's play this game!
var then = Date.now();
reset();
main();
我会补充一点,教程有点旧(2011),一些细节可以改进。例如,您可以使用 performance.now() instead of Date.now() as reported by lighthouse.