-
-
Save devyn/4513070 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<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.webkitRequestAnimationFrame(step); | |
} | |
var Character = function() { | |
this.x = 20; | |
this.y = 20; | |
this.w = 20; | |
this.h = 40; | |
this.vx = 0; | |
this.vy = 0; | |
}; | |
Character.prototype.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.prototype.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.prototype.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.prototype.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.webkitRequestAnimationFrame(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