Skip to content

Instantly share code, notes, and snippets.

@mmurray
Created February 13, 2011 07:58
Show Gist options
  • Save mmurray/824531 to your computer and use it in GitHub Desktop.
Save mmurray/824531 to your computer and use it in GitHub Desktop.
;
networld.Engine = (function($){
var $node,
ready = false,
keys = {},
mouse = {x:0,y:0},
cursor,
player,
netPlayers = {},
images,
socket,
loopInterval,
syncInterval;
var options = {},
defaults = {
node: null,
fps: 60,
syncRate: 0.1,
images: {},
cursor:null,
loadPlayer: function(){},
loadGameObjects: function(){},
loadCursor: function(){},
loop: function(){},
sync: function(){},
receiveData: function(){}
}
function init(o){
options = $.extend(true, defaults, o);
$node = $(options.node);
socket = new io.Socket();
socket.on('message', function(data){
options.receiveData.call({netPlayers:netPlayers, $node:$node, images:images}, data);
});
socket.connect();
loadAssets(function(){
loadPlayer();
loadGameObjects();
loadCursor();
attachEvents();
launch();
});
}
function loadCursor(){
cursor = options.loadCursor.call({$node:$node, images:images, mouse:mouse});
}
function loadAssets(callback, context){
images = new networld.ImageManager();
images.load(options.images, function(){
callback.call(context);
}, 20000);
}
function loadPlayer(){
player = options.loadPlayer.call({$node:$node, images:images, socket:socket});
}
function loadGameObjects(){
options.loadGameObjects.call(this, $node);
}
function attachEvents(){
$(window).keyup(function(e){
e.preventDefault();
if(keys[e.keyCode]){
keys[e.keyCode] = false;
}
});
$(window).keydown(function(e){
e.preventDefault();
if(!keys[e.keyCode]){
keys[e.keyCode] = true;
}
});
$(window).mousemove(function(e){
mouse.x = e.pageX;
mouse.y = e.pageY;
});
}
function sync(){
options.sync.call({player:player, netPlayers:netPlayers, keys:keys, mouse:mouse, socket:socket});
}
function loop(){
if(cursor != null){
cursor.x = mouse.x;
cursor.y = mouse.y;
cursor.update();
}
options.loop.call({player:player, netPlayers:netPlayers, keys:keys, mouse:mouse, cursor:cursor, socket:socket});
}
function launch(){
try{
loopInterval = setInterval(loop, 1000 / options.fps);
syncInterval = setInterval(sync, 1000 * options.syncRate);
}catch(e){
clearInterval(loopInterval);
clearInterval(syncInterval);
console.log(e);
throw(e);
}
}
return function(opts) {
init(opts);
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment