How does this game loop actually work?

Posted by Nicolai on Game Development See other posts from Game Development or by Nicolai
Published on 2014-06-10T21:32:41Z Indexed on 2014/06/10 21:48 UTC
Read the original article Hit count: 413

Filed under:
|

I read this playfulJS post, about ray-casting: http://www.playfuljs.com/a-first-person-engine-in-265-lines/

It looks really interested, so I decided to look at his javascript. I am no expert in javascript, so I quickly got lost.

It's the game loop "object" that really gets me. I simply don't understand how it works. From the code:

function GameLoop() {
        this.frame = this.frame.bind(this);
        this.lastTime = 0;
        this.callback = function() {};
      }

      GameLoop.prototype.start = function(callback) {
        this.callback = callback;
        requestAnimationFrame(this.frame);
      };

      GameLoop.prototype.frame = function(time) {
        var seconds = (time - this.lastTime) / 1000;
        this.lastTime = time;
        if (seconds < 0.2) this.callback(seconds);
        requestAnimationFrame(this.frame);
      };

var loop = new GameLoop();

      loop.start(function frame(seconds) {
        map.update(seconds);
        player.update(controls.states, map, seconds);
        camera.render(player, map);
      });

Now, what really confuses me here, is this bind stuff and how this actually loops.

I am guessing, that if less than 0.2 seconds have passed, since the last time the loop was run, it simply goes back to re-check the time. If more than 0.2 seconds have passed, it leaves the frame function, and executes the 3 lines in the loop.

But, if this is true, then how does the loop.start() get called again? And what on earth is the meaning of this.frame = this.frame.bind(this);?

I've looked up prototypes bind() but I really don't understand it.

© Game Development or respective owner

Related posts about JavaScript

Related posts about game-loop