Collision detection between a sprite and rectangle in canvas
- by Andy
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.