【问题标题】:Bounding box collision detection algorithm边界框碰撞检测算法
【发布时间】:2015-02-02 09:06:15
【问题描述】:

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

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】:

    它不是最好的,但它可能会帮助你。
    我有两个名为 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

    【讨论】:

      猜你喜欢
      • 2015-02-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多