Boxiom
Boxiom

Reputation: 2305

Bounding box collision detection algorithm

I am trying to make an algorithm for handling collision between two bounding boxes (my player, and some solid object) without using the sf::Rect intersects that SFML provides. Right now, this is how I detect the actual collision:

if (obstacle.GetPosition().x < p.getPlayerPosition().x + p.getPlayerSize().x &&
    obstacle.GetPosition().x + obstacle.GetSize().x > p.getPlayerPosition().x &&
    obstacle.GetPosition().y < p.getPlayerPosition().y + p.getPlayerSize().x &&
    obstacle.GetSize().y + obstacle.GetPosition().y > p.getPlayerPosition().y)
{
    // Collision
}

However, I also need to figure out on which of the obstacles four sides the player collides, so I can set the correct player position. Does anyone have any ideas on how this can be done as simple and effective as possible?

Upvotes: 1

Views: 1038

Answers (1)

singhiskng
singhiskng

Reputation: 511

it is not the best one but it might help you.
i have two boxes named box1 and box2

   var dx = box1.x - box2.x;
    var px = (box2.xw + box1.xw) - Math.abs(dx);//penetration depth in x

    if(0<px){
        var dy = box1.y - box2.y;
        var py = (box2.yw + box1.yw) - Math.abs(dy);//penetration depth in y

        if(0<py){

            // Collision detected 

            if(px < py){
                //project in x
                if(dx < 0){
                    //project to the left
                    px *= -1;
                    py *= 0;
                }
                else{
                    //proj to right
                    py = 0;
                }
            }
            else{               
                //project in y
                if(dy < 0){
                    //project up
                    px = 0;
                    py *= -1;
                }
                else{
                    //project down
                    px = 0;
                }
            }
            // we get px and py , penetration vector

            box1.x += px;
            box1.y += py;
        }
    }

here is the Example in javascript

Upvotes: 0

Related Questions