Collisions
by rudigerkidd
HTML
<p>Click the canvas to get it's focus</p>
<p>Use arrowkeys to move player (black box)</p>
<p>Player's outline will become red if hitting barrier</p>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body {
background-color: ivory;
padding:20px;
}
canvas {
border:1px solid red;
}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var defaultFill = "lightgray";
var defaultStroke = "skyblue";
ctx.fillStyle = defaultFill;
ctx.strokeStyle = defaultStroke;
var player = {
x: 0,
y: 0,
w: 20,
h: 20,
fill: "black",
stroke: "black"
};
console.log(player.fill);
var barriers = [];
barriers.push({
x: 50,
y: 100,
w: 40,
h: 30
});
barriers.push({
x: 200,
y: 230,
w: 20,
h: 20
});
barriers.push({
x: 150,
y: 100,
w: 20,
h: 20
});
barriers.push({
x: 150,
y: 200,
w: 20,
h: 20
});
barriers.push({
x: 240,
y: 25,
w: 10,
h: 150
});
drawAll();
function drawAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < barriers.length; i++) {
drawRect(barriers[i]);
}
drawRect(player, player.fill, player.stroke);
}
function drawRect(r, fill, stroke) {
ctx.beginPath();
ctx.rect(r.x, r.y, r.w, r.h);
ctx.closePath();
ctx.fillStyle = fill || defaultFill;
ctx.fill();
ctx.strokeStyle = stroke || defaultStroke;
ctx.stroke();
}
function movePlayer(desiredMoveX, desiredMoveY) {
// calculate where the player would like to be
var desiredPlayer = {
x: player.x + desiredMoveX,
y: player.y + desiredMoveY,
w: player.w,
h: player.h,
fill: "black",
stroke: "black"
}
// to start, set the move to be allowed
var allowMove = true;
// check every barrier for collisions
for (var i = 0; i < barriers.length; i++) {
// if the desiredPlayer has collided with a barrier
// set the allowMove flag to false
if (RectsColliding(desiredPlayer, barriers[i])) {
allowMove = false;
}
}
// if the move is allowed, return the desiredPlayer position
// if the move is not allowed, return the old player position
if (allowMove) {
player = desiredPlayer;
...