BlueGit

timfa frameworkv3

Files

frameworkv3 / framework / engine.js

engine.js

Framework 3
timfa Tim Falken · pushed by timfa · 9 years ago
4a56d325 History
engine.js 2.4 KiB Download Raw
1//engine
2
3var Engine =
4{
5 x: 0,
6 y: 0,
7 w: 0,
8 h: 0,//stored for window-building
9}
10
11//<DOC> category Game
12var Game =
13{
14 stepPrevious: 0,
15
16 //<DOC> <parameter> Game.activeObjects<br><br>array containing all existing objects.
17 activeObjects: [],
18 userUpdateCallback: null,
19
20 //<DOC> <parameter> Game.stepsSinceStart<br><br> Total amount of update steps since the start of the game.
21 stepsSinceStart: 0,
22
23 //<DOC> <function> Game.initialize(windowX, windowY, windowWidth, windowHeight, fps, loadedCallback)<br><br>Starts the game, and creates a window at ('windowX', 'windowY'), using 'windowWidth' and 'windowHeight' as sizes for the game window in pixels. 'fps' controls the game's frames-per-second'. As soon as the game is loaded up, it'll call the function 'loadedCallback', so you can properly start the game.
24 initialize: function(windowX, windowY, windowWidth, windowHeight, fps, loadedCallback)
25 {
26 console.log("GAME: Initializing. Loading dependencies...");
27 Engine.x = windowX;
28 Engine.y = windowY;
29 Engine.w = windowWidth;
30 Engine.h = windowHeight;
31
32 GameWindow.init(Engine.x, Engine.y, Engine.w, Engine.h);
33 GameInput.g_init();
34 window.setInterval(Game.gameStep, 1000 / fps);
35 loadedCallback();
36 },
37
38 //<DOC> <function> Game.setUpdateFunction(callback)<br><br>Assigns a function 'callback(deltaTime)' to be called every frame of the game. You can use this to run global code for your game.
39 setUpdateFunction: function(callback)
40 {
41 Game.userUpdateCallback = callback;
42 },
43
44 //<DOC> <function> Game.clearScene()<br><br>destroys every object in the scene.
45 clearScene: function()
46 {
47 for(var i = 0; i < Game.activeObjects.length; i++)
48 Game.activeObjects[i].destroy();
49 },
50
51 gameStep: function()
52 {
53 var stepTime = Date.now();
54
55 var stepTimeCurr = (stepTime - this.stepPrevious) * 0.001;
56
57 stepTimeCurr = Math.min(stepTimeCurr, 0.1);
58
59 if(isNaN(stepTimeCurr))
60 stepTimeCurr = 0;
61
62 Game.stepsSinceStart++;
63
64 GameInput.g_updateKeys();
65
66 var toUpdate = Game.activeObjects.slice();
67
68 for(var i = 0; i < toUpdate.length; i++)
69 {
70 if(toUpdate[i].active || toUpdate[i].destroyed)
71 toUpdate[i].g_updateStep(stepTimeCurr);
72 }
73
74 if (typeof Game.userUpdateCallback == 'function') { Game.userUpdateCallback(stepTimeCurr); }
75
76 GameWindow.redraw();
77
78 this.stepPrevious = stepTime;
79 },
80
81 reorderObjects: function()
82 {
83 this.activeObjects.sort(function(a, b)
84 {
85 return a.renderer.layerDepth - b.renderer.layerDepth;
86 })
87 }
88};