Page 1 of 1

Collision Detection

Posted: Sat May 02, 2009 9:38 pm
by Daxtorax
I was trying to create a function that detected collision between two objects. I was trying to have it depending on what number the integer col returned it would not allow the player to move in the direction of which it collided. After it not working successfully, I kept making minor changes and now it's the closest I've gotten it to working, but I seem to still not be doing something right, for in the case of col returning 2, meaning that your on the left side of the object, it simply doesn't detect collision. I've checked for collision detection tutorials on google, and generally they are for 3d games or only for checking for collision between the object and the screen. I greatly appreciate any help!

Code: Select all

int check_collision(int ob1x, int ob1y, int ob2x, int ob2y)
{
    int col = 0;
    int ob1xt;
    int ob1yt;
    int ob2xt;
    int ob2yt;
    int o2x;
    int o2xt;
    int o2y;
    int o2yt;
    ob1xt = ob1x + 32;
    ob1yt = ob1y + 32;
    ob2xt = ob2x + 32;
    ob2yt = ob2y + 32;
    o2y = ob2y -5;
    o2yt = ob2yt - 5;
    o2x = ob2x + 5;
    o2xt = ob2xt - 5;
    if ((ob1x <= ob2xt) && (ob1x > o2xt) && (ob1y <= ob2yt) && (ob1yt >= ob2y))
    {
        //Able to move Up, Down, Right
        col = 1;
    }
    if ((ob1xt >= ob2x) && (ob1xt < o2x) && (ob1y <= ob2yt) && (ob1yt >= ob2y))
    {
        //Able to move Up, Down, Left
        col = 2;
    }
    if ((ob1xt >= ob2x) && (ob1x <= ob2xt) && (ob1y <= ob2yt) && (ob1y > o2yt))
    {
        //Able to move Down, Left, Right
        col = 3;
    }
    if ((ob1xt >= ob2x) && (ob1x <= ob2xt) && (ob1yt >= ob2y) && (ob1yt < o2yt))
    {
        //Able to move Up, Left, Right
        col = 4;
    }
    return (col);

}

Re: Collision Detection

Posted: Sat May 02, 2009 10:02 pm
by Daxtorax
I should probably specify that my characters images are all 32 by 32.

Re: Collision Detection

Posted: Sun May 03, 2009 4:54 pm
by Joeyotrevor
You really only need to do something like this:

Code: Select all

bool check_collision(int x1, int y1, int x2, int y2)
{
if((x1 <= x2+32) && (x1 + 32 >= x2) && (y1 <= y2+32) && (y1 + 32 >= y2))
{
return true;
}
return false;
}
Then for your movement you would have:

Code: Select all

if(left key is down)
{
x -= 5;
//loop through all objects and check collosion
if(check_collision(x, y, ...)
{
x += 5;
}
}

Re: Collision Detection

Posted: Mon May 04, 2009 7:44 pm
by Daxtorax
Thanks! I managed to get mine to work, but it was slow in detecting it, thank you for your help!