Skip to content

Instantly share code, notes, and snippets.

@payne
Created January 31, 2014 02:33
Show Gist options
  • Save payne/8725683 to your computer and use it in GitHub Desktop.
Save payne/8725683 to your computer and use it in GitHub Desktop.
A Pen by Matt Payne.
<!DOCTYPE HTML>
<head>
<title>Something fancy</title>
</head>
<body>
From: <a href="http://www.somethinghitme.com/2013/01/09/creating-a-canvas-platformer-tutorial-part-one/">http://www.somethinghitme.com/2013/01/09/creating-a-canvas-platformer-tutorial-part-one/</a>
<h3>Arrow keys to move, and space to jump. v001</h3>
<canvas id="canvas"></canvas>
</body>
// What is lines 2-5? Document ready code?
/*(function() {
var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame;
})();*/
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var width = 500,
height = 200,
player = {
x : width/2,
y : height - 5,
width : 5,
height : 5,
speed: 3,
velX: 0,
velY: 0,
jumping: false
},
keys = [],
friction = 0.8,
gravity = 0.3;
canvas.width = width;
canvas.height = height;
function update(){
// check keys
if (keys[38] || keys[32]) {
// up arrow or space
if(!player.jumping){
player.jumping = true;
player.velY = -player.speed*2;
}
}
if (keys[39]) {
// right arrow
if (player.velX < player.speed) {
player.velX++;
}
}
if (keys[37]) {
// left arrow
if (player.velX > -player.speed) {
player.velX--;
}
}
player.velX *= friction;
player.velY += gravity;
player.x += player.velX;
player.y += player.velY;
if (player.x >= width-player.width) {
player.x = width-player.width;
} else if (player.x <= 0) {
player.x = 0;
}
if(player.y >= height-player.height){
player.y = height - player.height;
player.jumping = false;
}
ctx.clearRect(0,0,width,height);
ctx.fillStyle = "red";
ctx.fillRect(player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
}
document.body.addEventListener("keydown", function(e) {
keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keys[e.keyCode] = false;
});
window.addEventListener("load",function(){
update();
});
canvas{border:1px solid black;}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment