Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Created January 18, 2024 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssaurel/ef5abcd238e63cacd906a039b7647eaf to your computer and use it in GitHub Desktop.
Save ssaurel/ef5abcd238e63cacd906a039b7647eaf to your computer and use it in GitHub Desktop.
Step 6 for creating a Snake on SSaurel's Blog
gameloop(timestamp) {
// Calculate the number of seconds passed since the last frame
secondspassed = (timestamp - oldtimestamp) / 1000;
oldtimestamp = timestamp;
// Calculate fps
realfps = Math.round(1 / secondspassed);
if (this.keyup) {
this.dirx = 0;
this.diry = -1;
} else if (this.keydown) {
this.dirx = 0;
this.diry = 1;
} else if (this.keyleft) {
this.dirx = -1;
this.diry = 0;
} else if (this.keyright) {
this.dirx = 1;
this.diry = 0;
}
now = window.performance.now();
elapsed = now - then;
if (elapsed > this.fpsinterval) {
// Get ready for next frame by setting then=now, but also adjust for your
// specified fpsInterval not being a multiple of RAF's interval
then = now - (elapsed % this.fpsinterval);
this.move();
this.draw(realfps);
}
var self = this;
window.requestAnimationFrame(function (timestamp) {
self.gameloop(timestamp);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment