Created
February 26, 2019 18:37
-
-
Save romeuhcf/3c81fa263a7e3f8c9cf774c0bc1b9753 to your computer and use it in GitHub Desktop.
Basic game loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var canvas = document.getElementById('canvas'); | |
var ctx = canvas.getContext("2d"); | |
canvas.width = 400; canvas.height = 300; | |
var mousePos = {x: 0, y:0}; | |
var lastFrameTimeMs = 0, | |
maxFPS = 60, | |
delta = 0, | |
timestep = 1000 / 60, | |
fps = 60, | |
framesThisSecond = 0, | |
lastFpsUpdate = 0, | |
running = false, | |
started = false, | |
frameID = 0; | |
function drawInfo(data){ | |
var y = 10; | |
var step = 10; | |
Object.assign(data, data, { | |
fps: Math.ceil(fps), | |
mouseX: mousePos.x, | |
mouseY: mousePos.y | |
}); | |
ctx.fillStyle = 'navy'; | |
ctx.font = "10px Georgia"; | |
for (var k in data) { | |
ctx.fillText(k + ": " + data[k], 10, y); | |
y+=step; | |
} | |
} | |
//Get Mouse Position | |
function getMousePos(canvas, evt) { | |
var rect = canvas.getBoundingClientRect(); | |
return { | |
x: evt.clientX - rect.left, | |
y: evt.clientY - rect.top | |
}; | |
} | |
canvas.addEventListener("mousemove", function (evt) { | |
mousePos = getMousePos(canvas, evt); | |
}, false); | |
function panic() { | |
delta = 0; | |
} | |
function begin() { | |
ctx.clearRect(0,0,canvas.width, canvas.height); | |
} | |
function end(fps) { | |
drawInfo({}); | |
} | |
function stop() { | |
running = false; | |
started = false; | |
cancelAnimationFrame(frameID); | |
} | |
function start() { | |
if (!started) { | |
started = true; | |
frameID = requestAnimationFrame(function(timestamp) { | |
draw(1); | |
running = true; | |
lastFrameTimeMs = timestamp; | |
lastFpsUpdate = timestamp; | |
framesThisSecond = 0; | |
frameID = requestAnimationFrame(mainLoop); | |
}); | |
} | |
} | |
function mainLoop(timestamp) { | |
// Throttle the frame rate. | |
if (timestamp < lastFrameTimeMs + (1000 / maxFPS)) { | |
frameID = requestAnimationFrame(mainLoop); | |
return; | |
} | |
delta += timestamp - lastFrameTimeMs; | |
lastFrameTimeMs = timestamp; | |
begin(timestamp, delta); | |
if (timestamp > lastFpsUpdate + 1000) { | |
fps = 0.25 * framesThisSecond + 0.75 * fps; | |
lastFpsUpdate = timestamp; | |
framesThisSecond = 0; | |
} | |
framesThisSecond++; | |
var numUpdateSteps = 0; | |
while (delta >= timestep) { | |
update(timestep); | |
delta -= timestep; | |
if (++numUpdateSteps >= 240) { | |
panic(); | |
break; | |
} | |
} | |
draw(delta / timestep); | |
end(fps); | |
frameID = requestAnimationFrame(mainLoop); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment