Game Loops
C
#include <time.h>
double seconds(void) {
struct timespec t;
timespec_get(&t, TIME_UTC);
return (double)t.tv_sec + t.tv_nsec / 1e9;
}
void update(double dt) {
// Update your game here.
}
void draw(void) {
// Draw your game here.
}
int main(void) {
int running = 1;
double previous = seconds();
while (running) {
double now = seconds();
double dt = now - previous;
previous = now;
// Read input; set running = 0 to quit.
update(dt);
draw();
// Add a platform-specific wait to limit CPU use.
}
return 0;
}
JavaScript
function update(dt) {
// Update your game here.
}
function draw() {
// Draw your game here.
}
let running = true;
let previous = performance.now();
function loop(now) {
if (!running) return;
const dt = (now - previous) / 1000;
previous = now;
// Read input; set running = false to quit.
update(dt);
draw();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Nim
import std/[monotimes, os]
proc update(dt: float) =
discard # Update your game here.
proc draw() =
discard # Draw your game here.
var running = true
var previous = getMonoTime()
while running:
let now = getMonoTime()
let dt = float(now.ticks - previous.ticks) / 1_000_000_000.0
previous = now
# Read input; set running = false to quit.
update(dt)
draw()
sleep(1) # Briefly yield the CPU.
← All snippets