简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM