'use strict';

var Color = require( './math/color' );
var Object3D = require( './object3d' );
var Camera = require( './camera' );
var Renderer = require( './renderer/renderer' );

function Game() {
  this.canvas = document.createElement( 'canvas' );
  this.ctx = this.canvas.getContext( '2d' );

  this.running = false;
  this.pt = 0;
  this.t = 0;

  this.camera = new Camera( 90 );

  this.scene = new Object3D();
  this.ambient = new Color();

  this.renderer = new Renderer({
    ctx: this.ctx,
    ambient: this.ambient
  });

  this.tick = this.tick.bind( this );
  this.onUpdate = null;
}

Game.prototype.tick = function() {
  if ( !this.running ) {
    return;
  }

  this.update();
  this.draw();
  requestAnimationFrame( this.tick );
};

Game.prototype.update = function() {
  this.t = Date.now();
  var dt = this.t - this.pt;
  this.pt = this.t;

  if ( dt > 1e2 ) {
    dt = 1e2;
  }

  dt *= 1e-3;

  if ( this.onUpdate ) {
    this.onUpdate( dt );
  }

  this.scene.children.map(function( object ) {
    object.update( dt );
  });
};

Game.prototype.draw = function() {
  this.renderer.render( this.scene, this.camera );
};

Game.prototype.play = function() {
  this.running = true;
  this.pt = Date.now();
  requestAnimationFrame( this.tick );
};

Game.prototype.pause = function() {
  this.running = false;
};

Game.prototype.setSize = function( width, height ) {
  this.canvas.width  = width;
  this.canvas.height = height;
  this.camera.aspect = width / height;
  this.camera.updateProjectionMatrix();
};

module.exports = Game;

@@ -173,16 +173,34 @@
 er' );%0A%0A
+var dt = 1 / 60;%0A%0A
 function
@@ -331,16 +331,43 @@
  false;%0A
+  // Time in milliseconds.%0A
   this.p
@@ -386,16 +386,67 @@
 s.t = 0;
+%0A  // Accumulated time (in seconds).%0A  this.at = 0;
 %0A%0A  this
@@ -903,20 +903,29 @@
 ;%0A  var 
-dt =
+frameTime = (
  this.t 
@@ -933,16 +933,25 @@
  this.pt
+ ) * 1e-3
 ;%0A  this
@@ -976,33 +976,49 @@
 f ( 
-dt %3E 1e2 ) %7B%0A    dt = 1e2
+frameTime %3E 0.25 ) %7B%0A    frameTime = 0.25
 ;%0A  
@@ -1026,21 +1026,62 @@
 %0A%0A  
-dt *= 1e-3;%0A%0A
+this.at += frameTime;%0A%0A  while ( this.at %3E= dt )  %7B%0A  
   if
@@ -1105,16 +1105,18 @@
 ) %7B%0A    
+  
 this.onU
@@ -1128,23 +1128,27 @@
 ( dt );%0A
+  
   %7D%0A%0A  
+  
 this.sce
@@ -1188,16 +1188,18 @@
 ) %7B%0A    
+  
 object.u
@@ -1213,19 +1213,45 @@
 dt );%0A  
+  
 %7D);
+%0A%0A    this.at -= dt;%0A  %7D
 %0A%7D;%0A%0AGam

Fix your timestep.