Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dmirtyisme/27c981b4c2bdb2844589 to your computer and use it in GitHub Desktop.
Save dmirtyisme/27c981b4c2bdb2844589 to your computer and use it in GitHub Desktop.
Canvas: Walking Simulater (Sidescroller)
<canvas id="canvas"></canvas>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
window.onresize = (function resize() {
canvas.setAttribute('width', window.innerWidth);
canvas.setAttribute('height', window.innerHeight);
return resize;
})();
requestAnimationFrame(function draw() {
drawBackground('orange', 0);
drawBackground('pink', 1);
drawBackground('aqua', 2);
drawBackground('lightgray', 3);
context.fillStyle = 'black';
var cubeSize = 50; // this will be the size of our cube
context.fillRect((window.innerWidth - cubeSize) / 2, window.innerHeight - cubeSize, cubeSize, cubeSize);
requestAnimationFrame(draw); // keep drawing after this
});
function drawBackground(color, position) {
context.fillStyle = color; // fillStyle is the current color to draw in
context.fillRect((position * window.innerWidth) - x, 0, window.innerWidth, window.innerHeight);
}
var left = false; // when true, the left arrow key is down
var right = false; // when true, the right arrow key is down
// this listens for when left/right are pressed
document.addEventListener('keydown', function(e) {
if (e.keyCode === 37) { // left
left = true;
} else if (e.keyCode === 39) { // right
right = true;
}
});
document.addEventListener('keyup', function(e) {
if (e.keyCode === 37) { // left
left = false;
} else if (e.keyCode === 39) { // right
right = false;
}
});
var down = false;
// touch events
document.addEventListener('pointerdown', function(e) {
if (e.clientX < window.innerWidth / 2) {
left = true;
} else if (e.clientX > window.innerWidth / 2) {
right = true;
}
down = true;
return false;
});
document.addEventListener('pointermove', function(e) {
if (down) {
if (e.clientX < window.innerWidth / 2) {
left = true;
right = false;
} else if (e.clientX > window.innerWidth / 2) {
right = true;
left = false;
}
}
});
document.addEventListener('pointerup', function(e) {
left = right = down = false;
});
var x = 0;
setInterval(function moveCube() {
if (left && !right) {
if (x > 0) {
x -= 10;
}
} else if (right && !left) {
// we have 4 backgrounds spanning the width of the window, so keep it inside of that
if (x < window.innerWidth * 3) {
x += 10;
}
}
}, 10);
<script src="//cdn.jsdelivr.net/handjs/1.3.8/hand.min.js"></script>
html, body, canvas {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
-ms-touch-action: pan-x;
touch-action: pan-x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment