Last active
March 16, 2018 22:47
-
-
Save nickworks/76273efddf085386aa0704f4243c4104 to your computer and use it in GitHub Desktop.
Some boilerplate code for setting up a game in vanilla JavaScript
This file contains 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
const canvas = document.getElementById("myCanvas"); | |
const gfx = canvas.getContext("2d"); | |
const keycode = { | |
w: 87, | |
a: 65, | |
s: 83, | |
d: 68, | |
left: 37, | |
up:38, | |
right:39, | |
down:40, | |
space:32, | |
enter:13, | |
escape:27 | |
}; | |
const keyboard = { | |
keys:[], | |
prev:[], | |
isDown:function(keyCode){ | |
return this.keys[keyCode] || false; // if the value is undefined, it will return false instead... | |
}, | |
onDown:function(keyCode){ | |
return (this.isDown(keyCode) && (this.prev[keyCode] || false) == false); | |
}, | |
update:function(){ | |
this.prev = this.keys.slice(0); // copy the array | |
}, | |
updateKey: function(keyCode, value){ | |
//console.log(keyCode + (value ? " down" : " up")); | |
this.keys[keyCode] = value; | |
}, | |
setup: function(){ | |
document.addEventListener("keydown", (e)=>this.updateKey(e.keyCode, true)); | |
document.addEventListener("keyup", (e)=>this.updateKey(e.keyCode, false)); | |
} | |
}; | |
const mouse = { | |
x: 0, | |
y: 0, | |
setup: function(){ | |
canvas.addEventListener("mousemove", (e)=>{ | |
this.x = e.offsetX; | |
this.y = e.offsetY; | |
}); | |
} | |
}; | |
const game = { | |
timePrev: 0, | |
dt: 0, | |
begin:function(){ | |
mouse.update(); | |
keyboard.setup(); | |
this.update(0); | |
}, | |
calcDeltaTime:function(time){ | |
if(time === undefined) time = 0; | |
this.dt = (time - this.timePrev) / 1000; | |
this.timePrev = time; | |
}, | |
update:function(time){ | |
this.calcDeltaTime(time); | |
if(keyboard.onDown(keycode.w)){ | |
console.log("W pressed!"); | |
} | |
keyboard.update(); | |
requestAnimationFrame((time) => this.update(time)); | |
} | |
}; | |
game.begin(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment