-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameloop.mjs
67 lines (59 loc) · 2.05 KB
/
gameloop.mjs
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
import { performance } from "perf_hooks";
class GameLoop {
constructor(delay, gameState) {
this.delay = delay;
this.gameState = gameState;
this.callbackHandle = 0;
this.lastFrame = null;
}
start(once = false) {
this.once = once;
this.redraw();
}
redraw() {
const fpsHistory = [];
let fpsOutputCounter = 0;
const draw = () => {
if (this.callbackHandle == 0) {
// just in case the cancel did not work
return;
}
const timestamp = performance.now();
const timeDelta = (timestamp - (this.lastFrame ?? timestamp)) / 1000;
this.lastFrame = timestamp;
const fps = 1 / timeDelta;
fpsHistory.length >= 30 && fpsHistory.shift();
isFinite(fps) && fpsHistory.push(fps);
if (++fpsOutputCounter > 300) {
const fpsMean = (fpsHistory.reduce((a, v) => a + v, 0) / fpsHistory.length).toFixed(1);
const fpsMin = Math.min(...fpsHistory).toFixed(1);
const fpsMax = Math.max(...fpsHistory).toFixed(1);
console.log(`FPS Mean: ${fpsMean} Min: ${fpsMin} Max: ${fpsMax}`);
fpsOutputCounter = 0;
}
this.callbackHandle = 0;
this.gameState.update(timeDelta);
if (!this.once && this.gameState.playerCount() > 0) {
this.callbackHandle = setTimeout(draw, this.delay * 1000);
} else {
console.log("Gameloop stopped");
}
}
if (this.gameState != null && this.callbackHandle == 0) {
this.callbackHandle = setTimeout(draw, this.delay * 1000);
console.log("Gameloop started");
}
}
stop() {
if (this.callbackHandle != 0) {
window.clearTimeout(this.callbackHandle);
}
this.callbackHandle = 0;
}
dispose() {
stop();
this.gameState = null;
}
}
GameLoop.prototype.start.ONCE = true;
export { GameLoop };