# Collision detection between a sprite and rectangle in canvas

I'm building a Javascript + canvas game which is essentially a platformer. I have the player all set up and he's running, jumping and falling, but I'm having trouble with the collision detection between the player and blocks (the blocks will essentially be the platforms that the player moves on).

The blocks are stored in an array like this:

var blockList = [[50, 400, 100, 100]];


And drawn to the canvas using this:

this.draw = function() {
c.fillRect(blockList[0][0], blockList[0][1], 100, 100);
}


I'm checking for collisions using something along these lines in the player object:

this.update = function() {
// Check for collitions with blocks
for(var i = 0; i < blockList.length; i++) {
if((player.xpos + 34) > blockList[i][0] && player.ypos > blockList[i][1]) {
player.xpos = blockList[i][0] - 28;
return false;
}
}

// Other code to move the player based on keyboard input etc
}


The idea is if the player will collide with a block in the next game update (the game uses a main loop running at 60Htz), the function will return false and exit, thus meaning the player won't move.

Unfortunately, that only works when the player hits the left side of the block, and I can't work out how to make it so the player stops if it hits any side of the block. I have the properties player.xpos and player.ypos to help here.

• Why are you using fillrect(..., 100, 100) instead of (..., blocklist[i][2], blocklist[i][3])? Commented Nov 3, 2011 at 14:14

if(player.xpos < blockList[i][0] + blockList[i][2] && player.xpos + player.width > (blockList[i][0] + blockList[i][2]) && player.ypos > blockList[i][1] && player.ypos + player.height < blockList[i][1] + blockList[i][3]){

Note that I've used player.width and player.height instead of hard-coded values. It'll help you later.
So what we're checking for here is if the player's right side is ahead of the block and if it's left side is less than the block's right side, while also being in the same y-positions. I'd recommend changing your current code to check for all 4 possibilities like my code up there did, because that's what will ensure that //Your code is executed only and only if it is colliding. Without checking for the y co-ordinates, the player wouldn't be able to jump over, or go under blocks. And without the 2 x co-ordinate checks, the code to be executed for a collision on the right, would be executed even if the player was on the left of the block.