HTML5 platformer collision detection problem

Posted by fnx on Game Development See other posts from Game Development or by fnx
Published on 2012-12-07T18:22:08Z Indexed on 2012/12/07 23:44 UTC
Read the original article Hit count: 205

I'm working on a 2D platformer game, and I'm having a lot of trouble with collision detection. I've looked trough some tutorials, questions asked here and Stackoverflow, but I guess I'm just too dumb to understand what's wrong with my code.

I've wanted to make simple bounding box style collisions and ability to determine on which side of the box the collision happens, but no matter what I do, I always get some weird glitches, like the player gets stuck on the wall or the jumping is jittery. You can test the game here: Platform engine test. Arrow keys move and z = run, x = jump, c = shoot. Try to jump into the first pit and slide on the wall.

Here's the collision detection code:

function checkCollisions(a, b)
{
    if  ((a.x > b.x + b.width) ||
        (a.x + a.width < b.x) ||
        (a.y > b.y + b.height) ||
        (a.y + a.height < b.y))
    {
        return false;
    }
    else
    {
        handleCollisions(a, b);
        return true;
    }
}

function handleCollisions(a, b)
{
    var a_top = a.y,
        a_bottom = a.y + a.height,
        a_left = a.x,
        a_right = a.x + a.width,
        b_top = b.y,
        b_bottom = b.y + b.height,
        b_left = b.x,
        b_right = b.x + b.width;

        if (a_bottom + a.vy > b_top && distanceBetween(a_bottom, b_top) + a.vy < distanceBetween(a_bottom, b_bottom))
        {
            a.topCollision = true;
            a.y = b.y - a.height + 2;
            a.vy = 0;
            a.canJump = true;
        }
        else if (a_top + a.vy < b_bottom && distanceBetween(a_top, b_bottom) + a.vy < distanceBetween(a_top, b_top))
        {
            a.bottomCollision = true;
            a.y = b.y + b.height;
            a.vy = 0;
        }

        else if (a_right + a.vx > b_left && distanceBetween(a_right, b_left) < distanceBetween(a_right, b_right))
        {
            a.rightCollision = true;
            a.x = b.x - a.width - 3;
            //a.vx = 0;
        }
        else if (a_left + a.vx < b_right && distanceBetween(a_left, b_right) < distanceBetween(a_left, b_left))
        {
            a.leftCollision = true;
            a.x = b.x + b.width + 3;
            //a.vx = 0;
        }

}
function distanceBetween(a, b)
{
    return Math.abs(b-a);
}

© Game Development or respective owner

Related posts about collision-detection

Related posts about JavaScript