JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div id="debug"><button style="float:right" onclick="g.pause()">||</button></div>
<script src="marc.js"></script>
</body>
JavaScript
let g = {
ui: {
fps: 60
}
,stats: {}
,state: ""
};
const dp = console.log.bind();
const $ = document.querySelector.bind(document);
// Setup rendering surface
g.ui.canvas = document.createElement("canvas");
g.ui.canvas.width = 400;
g.ui.canvas.height = 400;
g.ctx = g.ui.canvas.getContext("2d");
document.body.appendChild(g.ui.canvas);
g.start = function() {
g.ui.frameMillis = 1000 / g.ui.fps;
g.stats.lastDrawTime = performance.now();
g.stats.lastSampleTime = g.stats.lastDrawTime;
g.stats.frameCount = 0;
console.clear();
dp("START**************");
g.gameLoop();
setInterval(g.stats.show, 100); // Show FPS every 100ms
}
g.stats.show = function() {
let now = window.performance.now();
if (g.stats.frameCount > 0) {
g.stats.currentFps = (g.stats.frameCount / (now - g.stats.lastSampleTime) * 1000).toFixed(2);// dp(g.stats.currentFps + " fps");
g.stats.frameCount = 0;
}
g.stats.lastSampleTime = now;
}
g.gameLoop = function() {
requestAnimationFrame(g.gameLoop);
if (g.state=="pause") return;
let now = window.performance.now();
let elapsed = now - g.stats.lastDrawTime;
// 2s passed without drawing -> pause game
if (elapsed>2000) {
dp("pausing");
return g.state="pause";
}
//dp(`Now ${now}, Elapsed ${elapsed}`)
// if enough time has elapsed, draw the next frame
if (elapsed > g.ui.frameMillis) {
//dp("Now", now.toFixed(2), "LastDrawTime2", g.stats.lastDrawTime.toFixed(2), "Elapsed", elapsed.toFixed(2), "Current FPS", g.stats.currentFps)
g.stats.lastDrawTime = now - (elapsed % g.ui.frameMillis);
// draw
g.gameRun(elapsed);
g.stats.graph.tick();
g.stats.frameCount++;
}
}
g.pause=function() {
if (g.state=="pause") {
g.state="";
g.stats.lastDrawTime=window.performance.now();
} else {
g.state="pause";
}
}
let Vector = function(x, y) {
this.x = x || 0;
this.y = y || 0;
this.area = () => this.x * this.y;
};
g.restart = function() {
g.scenes = {
menu: {entities: []}
,level1: {entities: []}
};
g.scene =...