边界框碰撞检测算法

问题描述 投票:1回答:1

我试图制作一个算法来处理两个边界框(我的播放器和一些实体对象)之间的碰撞,而不使用SFML提供的sf :: Rect相交。现在,这是我检测实际碰撞的方式:

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
}

但是,我还需要弄清楚玩家碰撞的四个障碍,所以我可以设置正确的玩家位置。有没有人对如何做到尽可能简单有效有任何想法?

c++ collision-detection sfml
1个回答
0
投票

它不是最好的,但它可能会帮助你。 我有两个名为box1box2的盒子

   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;
        }
    }

这是javascript中的Example

© www.soinside.com 2019 - 2024. All rights reserved.