【问题标题】:Collision Detection and Time Complexity: How do I make checking for collisions easier?碰撞检测和时间复杂度:如何更轻松地检查碰撞?
【发布时间】:2012-07-07 06:06:26
【问题描述】:

我正在尝试编写一个程序来处理各种对象的检测。对象具有原点、宽度、高度和速度。有没有办法设置数据结构/算法,以便每个对象都不会与其他所有对象进行检查?

我试图避免的问题的一些示例代码:

for (int i = 0; i < ballCount; i++)  
{  
    for (int j = i + 1; j < ballCount; j++)  
    {  
        if (balls[i].colliding(balls[j]))  
        {
            balls[i].resolveCollision(balls[j]);
       }
    }
}

【问题讨论】:

  • 我不认为你可以让它比你目前正在做的事情更容易,但是你可以让它更快。你问的是这个吗?

标签: c++ c collision-detection


【解决方案1】:

您可以使用quadtree 快速找到与另一个矩形相交的所有矩形。如果需要处理非矩形的形状,可以先找到bounding boxes相交的对象。

四叉树的一些常见用途

  • ...
  • 高效的二维碰撞检测
  • ...

【讨论】:

    【解决方案2】:

    正如其他答案所提到的,您可以使用四叉树结构来加快碰撞检测。

    我会推荐 GEOS 开源 C++ 库,它具有良好的四叉树实现。 Here are the docs for their quadtree class.

    所以你的伪代码应该是这样的:

    Quadtree quadtree;
    // Create and populate the quadtree.
    // Change it whenever the balls move.
    
    // Here's the intersection loop:
    for (int i=0; i<ballCount; ++i) {
        Envelope envelope = ...;  // Get the bounds (envelope) of ball i
        std::vector<void*> possiblyIntersectingBalls;
        quadtree.query(envelope, possiblyIntersectingBalls);
        // Now loop over the members of possiblyIntersectingBalls to check
        // if they really intersect, since quadtree only checks bounding
        // box intersection.
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2021-12-18
      相关资源
      最近更新 更多