View Single Post
  #1 (permalink)  
Old June 4th, 2013, 06:57 PM
ragnarok ragnarok is offline
Registered User
Points: 20, Level: 1
Points: 20, Level: 1 Points: 20, Level: 1 Points: 20, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2013
Posts: 2
Thanks: 0
Thanked 2 Times in 2 Posts
Default DeltaTime initialisation

I enjoy the book so far very much (and love to see that Quintus is expanded as it's own project), however sometimes I got a strange bug with the initialisation of dt (delta time).

I got in the first chapters but, couldn't recreate it reliable. However with Chapter 17 and the canon-physics-demo I ran into it again.

I finally have a little clue: I happen to get the bug with Chrome. With Firefox it works.

Using "canon2.html" from Chapter 17 on Chrome 27 on Windows 8. I just added the follwing two lines to the code (before and) in the game loop, to get a clue what's going on.

Code:
      var first=true;
      Q.gameLoop(function(dt) {      
        if (first) {console.log(dt); first=false;}
        Q.clear(); 

        ball1.step(dt);
        ball1.draw(Q.ctx);

        ball2.step(dt);
        ball2.draw(Q.ctx);
      });
This revealed a "dt" of something like -1370384577.078 (always about this number. sometimes a little less, sometimes a little more), resulting in sprites that were placed far below/behind the canvas. On Firefox this nets me something like 0.12 which is expected.

Going further(quick and dirty again):
Code:
Q.gameLoop = function(callback) {
    var loopnumber=0;
    Q.lastGameLoopFrame = new Date().getTime();

    Q.gameLoopCallbackWrapper = function(now) {
       /*mine*/if (loopnumber==0) {console.log(now);}

      Q.loop = requestAnimationFrame(Q.gameLoopCallbackWrapper);
      var dt = now - Q.lastGameLoopFrame;

       /*mine*/if (loopnumber==0) {console.log(dt); loopnumber++;}

      if(dt > 100) { dt = 100; }
      callback.apply(Q,[dt / 1000]);  
      Q.lastGameLoopFrame = now;
    };
This reveals, that "now" is something along the lines of 120 (resulting in a negative "dt" a few lines later). My workaround for this is:

Code:
Q.gameLoop = function(callback) {
    var firstloop=true;
    Q.lastGameLoopFrame = new Date().getTime();

    Q.gameLoopCallbackWrapper = function(now) {
      /*Workaround*/ if (firstloop) {Q.lastGameLoopFrame =now);firstloop=false;}

      Q.loop = requestAnimationFrame(Q.gameLoopCallbackWrapper);
      var dt = now - Q.lastGameLoopFrame;

      if(dt > 100) { dt = 100; }
      callback.apply(Q,[dt / 1000]);  
      Q.lastGameLoopFrame = now;
    };
This works on Firefox and Chrome, but:
A) Is something broken in Chrome, or is it somehow my fault?
B) Making an (otherwise) unecessarry query ''if (firstloop)' bugs me. Is there a more elegant solution?

Last edited by ragnarok; June 4th, 2013 at 07:00 PM.
The Following User Says Thank You to ragnarok For This Useful Post:
sauerkraut (June 5th, 2013)