Skip to content

Commit

Permalink
added time and context to the gameLoop
Browse files Browse the repository at this point in the history
  • Loading branch information
numso committed Mar 8, 2013
1 parent f0b349b commit 442cc68
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 12 deletions.
39 changes: 30 additions & 9 deletions client/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ var render = require('./requires/render')
, shared = require('./shared')
;

$.get('/getHighScores', function(data){
shared.scores = JSON.parse(data);
});

// Load all the states
var states = {
menu: require('./states/menu'),
Expand All @@ -17,16 +13,37 @@ var states = {
settings: require('./states/settings')
};

var lastTime, ctx;

function init() {
window.requestAnimationFrame = window.requestAnimationFrame; // FIX THIS
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (cb) { window.setTimeout(cb, 1000 / 60); };

// get the high scores from the server
getScores();

// initialize all the states
initStates();

// set the current state
shared.setState(states.menu);

// set up the context
var canvas = document.getElementById('#game');
ctx = canvas.getContext('2d');

// set up the time
lastTime = Date.now();

// start the game loop
requestAnimationFrame(gameLoop);
};

function getScores() {
$.get('/getHighScores', function (data) {
shared.scores = JSON.parse(data);
});
};

function initStates() {
for (var state in states) {
states[state].init = states[state].init || shared.nop;
Expand All @@ -40,13 +57,17 @@ function initStates() {
};

function gameLoop() {
// request to be called again in the next animation loop
// this needs to be done first to support older browsers
requestAnimationFrame(gameLoop);

// MANAGE THE TIMES
shared.getState().update();
// get the time difference, but cap it at 20ms
var curTime = Date.now()
, dTime = curTime - lastTime;
if (dTime > 20) dTime = 20;

// GRAB THE CONTEXT
shared.getState().render();
shared.getState().update(dTime);
shared.getState().render(ctx);
};

init();
5 changes: 2 additions & 3 deletions views/index/index.jade
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
extends ../layout

block content
.gameScreen

canvas#game
.gameScreen
canvas#game

0 comments on commit 442cc68

Please sign in to comment.