timing for simulations and games for node and the browser
Here is a simple game where you can drive a purple square with the keyboard:
var loop = require('frame-loop');
var keyname = require('keynames');
var player = document.querySelector('#player');
var pos = { x: 200, y: 200 };
var vel = { x: 0, y: 0 };
var engine = loop(function (dt) {
pos.x += vel.x * dt / 5;
pos.y += vel.y * dt / 5;
player.style.left = pos.x;
player.style.top = pos.y;
});
engine.run();
engine.on('fps', function (fps) {
console.log('fps=', fps);
});
window.addEventListener('keydown', function (ev) {
var name = keyname[ev.which];
if (name === 'left') vel.x = -1;
if (name === 'right') vel.x = 1;
if (name === 'up') vel.y = -1;
if (name === 'down') vel.y = 1;
});
window.addEventListener('keyup', function (ev) {
var name = keyname[ev.which];
if (name === 'left' || name === 'right') vel.x = 0;
if (name === 'up' || name === 'down') vel.y = 0;
});
and the html:
<!doctype html5>
<html>
<head>
<style>
#player {
position: absolute;
background-color: purple;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="player"></div>
<script src="bundle.js"></script>
</body>
</html>
Compile with browserify:
$ browserify loop.js > bundle.js
var loop = require('frame-loop')
If a function fn(dt)
is given, it will be registered as a listener for the
'tick'
event.
opts
are:
opts.fps
- the target fps to aim for, default: 60opts.fpsWindow
- how often to emit the'fps'
event in milliseconds, default: 1000opts.requestFrame
- the function to use to request a frame
If opts.requestFrame
isn't provided, it will be detected dynamically.
In the browser, opts.requestFrame
defaults to window.requestAnimationFrame
or self.requestAnimationFrame
.
On the server, opts.requestFrame
defaults to setImmediate
or
setTimeout(fn, 0)
.
Start or unpause the engine.
Stop the engine.
If the engine was running, pause it. Otherwise, run the engine.
Schedule an event fn
to happen in time
milliseconds of game time.
Clear a timeout to
created with engine.setTimeout()
.
Schedule an event fn
to happen every time
milliseconds of game time.
Clear a timeout iv
created with engine.setInterval()
.
A boolean indicating whether the engine is paused or running.
The monotonically-increasing game time in milliseconds.
Whenever a frame is rendered, a tick event fires with the time difference
between frames, dt
in milliseconds.
Every fpsWindow (default: 1000ms), this event fires with the calculated frames
per second fps
.
With npm do:
npm install frame-loop
MIT