Skip to content

Instantly share code, notes, and snippets.

Created January 11, 2013 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/4513061 to your computer and use it in GitHub Desktop.
Save anonymous/4513061 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Game</title>
<script>
var g, lt = Date.now();
var scene = [];
function step() {
var ot = lt;
var dt = (lt = Date.now()) - ot;
var w = parseInt(g.canvas.width,10), h = parseInt(g.canvas.height,10);
g.clearRect(0, 0, w, h);
for (var i = 0; i < scene.length; i++) {
scene[i].step(dt, w, h);
scene[i].draw(g, w, h);
}
window.requestAnimationFrame(step);
}
var Character = function() {
this.x = 20;
this.y = 20;
this.w = 20;
this.h = 40;
this.vx = 0;
this.vy = 0;
};
Character.step = function(dt, width, height) {
this.vy -= 9.8*dt/1000; // gravity
if (this.y <= height-this.h) {
this.vy = 0;
this.y = height-this.h;
}
this.x += this.vx*dt/100;
this.y += this.vy*dt/100;
};
Character.draw = function(g) {
g.save();
g.fillStyle = "#55f";
g.fillRect(this.x, this.y, this.w, this.h);
g.restore();
};
var LEFT_ARROW = 39
, UP_ARROW = 40
, DOWN_ARROW = 41
, RIGHT_ARROW = 42
;
Character.keydown = function(e) {
switch (e.keyCode) {
case LEFT_ARROW:
this.vx -= 3;
break;
case RIGHT_ARROW:
this.vx += 3;
break;
case UP_ARROW:
this.vy += 20;
break;
}
};
Character.keyup = function(e) {
switch (e.keyCode) {
case LEFT_ARROW:
this.vx += 3;
break;
case RIGHT_ARROW:
this.vx -= 3;
break;
}
};
window.onload = function() {
window.onkeydown = function(e) {
for (var i = 0; i < scene.length; i++) if (scene[i].keydown) scene[i].keydown(e);
};
window.onkeyup = function(e) {
for (var i = 0; i < scene.length; i++) if (scene[i].keyup) scene[i].keyup(e);
};
g = document.getElementById("mainCanvas").getContext("2d");
scene.push(new Character);
window.requestAnimationFrame(step);
window.onresize = function() {
g.canvas.width = window.clientWidth;
g.canvas.height = window.clientHeight;
};
};
</script>
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="mainCanvas" width="640" height="480"></canvas>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment