I programmed canvas collision into my html game. I have checked numerous times but I cant find a problem with the code.
// Handle left and right collisions with the canvas
if (player.x <= canvas.x) {
// Left edige
player.xdir = 1;
player.x = canvas.x;
} else if (player.x + player.width >= canvas.x + canvas.width) {
// Right edge
player.xdir = -1;
player.x = canvas.x + canvas.width - player.width;
}
// Handle top and bottom collisions with the canvas
if (player.y <= canvas.y) {
// Top edge
player.ydir = 1;
player.y = canvas.y;
} else if (player.y + player.height >= canvas.y + canvas.height) {
// Bottom edge
player.ydir = -1;
player.y = canvas.y + canvas.height - player.height;
}
I think the canvas.x
thing is misunderstood. Everything in canvas is always absolute relative to the canvas' point of origin:
//Polyfill for "requestAnimationFrame"
window.requestAnimationFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
setTimeout(callback, 1000 / 60);
};
//The player object
var player = {
x: 50,
y: 150,
xdir: 1,
ydir: 1,
width: 10,
height: 10
};
//The canvas (creation and appending)
var canvas = document.body.appendChild(document.createElement("canvas"));
canvas.height = 200;
canvas.width = canvas.height;
//Rendering context
var ctx = canvas.getContext("2d");
function simulate() {
//Move player
if (player.xdir === 1) {
player.x += 1;
} else {
player.x -= 1;
}
if (player.ydir === 1) {
player.y += 1;
} else {
player.y -= 1;
}
// Handle left and right collisions with the canvas
if (player.x <= player.width * 0.5) {
// Left edige
player.xdir = 1;
} else if (player.x + player.width >= canvas.width + player.width * 0.5) {
// Right edge
player.xdir = -1;
}
// Handle top and bottom collisions with the canvas
if (player.y <= player.height * 0.5) {
// Top edge
player.ydir = 1;
} else if (player.y + player.height >= canvas.height + player.height * 0.5) {
// Bottom edge
player.ydir = -1;
}
requestAnimationFrame(simulate);
//Draw the player (just for fun)
ctx.fillStyle = "rgba(235,235,255,0.1)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.fillRect(player.x - 0.5 * player.width, player.y - 0.5 * player.height, player.width, player.height);
}
//Start simulation
simulate();
canvas {
background-color: rgba(235, 235, 255, 0.1);
}