-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGameLoop.js
More file actions
107 lines (101 loc) · 3.34 KB
/
GameLoop.js
File metadata and controls
107 lines (101 loc) · 3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
(function() {
var context = this;
/*
Parameters in config [default]
fps = integer, default 60
fpsMode = string, ['fixed'] 'screenHz'
autoStart = boolean, [false]
createDebugKeyBoardShortcuts = boolean, [false]
*/
class GameLoop {
constructor(config) {
if (config === null) {
config = {}
}
if (typeof config === 'function') {
this.callback = config;
} else {
this.callback = config.callback || function() {};
}
if (config.fps && config.fpsMode && config.fpsMode === 'screenHz')
console.warn('GameLoop config: Don\'t set FPS when setting fpsMode screenHz, it\'s irrelevant and framerate will still be locked to screen framerate.')
this.fps = config.fps || 60;
this.fpsMode = config.fpsMode || 'fixed';
this.playing = config.autoStart !== false;
this.createDebugKeyBoardShortcuts = config.createDebugKeyBoardShortcuts || false;
this.interval = null;
this.previousFrame = null;
if (this.createDebugKeyBoardShortcuts)
this.createShortcuts();
if (this.playing) {
this.start();
}
}
createShortcuts() {
context.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 80:
this.toggle();
break;
}
}.bind(this))
}
determineDiff() {
var prev = this.previousFrame;
this.previousFrame = Date.now();
if (prev) {
return Math.min(Date.now() - prev, 16.666666);
} else {
return 16; //First frame is free
}
}
start() {
this.playing = true;
function wrappedLoop() {
if (this.fpsMode === 'screenHz') {
context.requestAnimationFrame(wrappedLoop.bind(this));
}
if (this.playing) {
this.callback(this.determineDiff());
}
}
switch(this.fpsMode) {
case 'fixed':
this.interval = context.setInterval(wrappedLoop.bind(this), 1000/this.fps);
break;
case 'screenHz':
context.requestAnimationFrame(wrappedLoop.bind(this));
break;
}
}
toggle() {
this.playing = !this.playing;
this.resetTime();
}
pause() {
this.playing = false;
}
play() {
this.playing = true;
this.resetTime();
}
stop() {
clearInterval(this.interval);
}
resetTime() {
this.previousFrame = Date.now();
}
};
if (typeof define !== 'undefined') {
define('GameLoop', [], function() {
return GameLoop;
});
} else if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = GameLoop;
}
exports.GameLoop = GameLoop;
} else {
this.GameLoop = GameLoop;
}
}.bind(this))();