Collision detection between a sprite and rectangle in canvas

Posted by Andy on Game Development See other posts from Game Development or by Andy
Published on 2011-11-02T23:42:07Z Indexed on 2011/11/23 10:12 UTC
Read the original article Hit count: 220

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.

© Game Development or respective owner

Related posts about collision-detection

Related posts about JavaScript