-2

I've used this tutorial to help me out writing a simple JS game for my school assignment. However I am now looking at the gameloop and I have no clue how this particular function is working.

Here is the URL of the tutorial. The block of code you're looking for is at 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);
};
Melvin
  • 27
  • 6
  • I'm voting to close this question as off-topic because it is asking to find a declaration in some example source code – rlemon Apr 09 '17 at 12:33
  • `then` is undoubtedly declared in a higher scope of the hierarchy of a - most probably - master closure. The expression function variable 'main' is being used to (undoubtedly) update the time interval between calls and render a corresponding frame; updates 'then` to `now` making it ready for subsequent `requestAnimationFrame` calling this same expression (main), to make a new update and `delta` calc. – Bekim Bacaj Apr 09 '17 at 12:40

2 Answers2

0

Read Start Game Number 10:

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

The following description also:

"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."

yass
  • 849
  • 1
  • 7
  • 13
0

I will try to explain what I understood from the code in the tutorial.
A game often runs in a fixed framerate, like 60 frames per seconds (FPS).
In the tutorial, that is not the case. Instead of having a fixed framerate and moving the character at a fixed distance in the update function, you have a delta variable used to calculate the distance.

hero.y -= hero.speed * modifier; // modifier is (delta / 1000)

Like the other answers said, then is set in the beginning, in the outer scope of the main function.

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

I will add that the tutorial is a little old (2011) and some details can be improved. For example, you can use performance.now() instead of Date.now() as reported by lighthouse.

Ffloriel
  • 408
  • 3
  • 10