Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-dimensional bounding box collision detection

There are answers for 2D/3D bounding box collision detection, however my problem is how to develop the situation to multi-dimension (4D or more) ?

Here is the code on 3D case.

template<typename T, typename _Prd>
bool BoundingBox3<T,_Prd>::Collision( const BoundingBox3<T,_Prd>& cube ) const
{

    Point3<T,_Prd> min_1 = center - Point3<T,_Prd>(length,depth,height)/2.0;
    Point3<T,_Prd> max_1 = center + Point3<T,_Prd>(length,depth,height)/2.0;

    Point3<T,_Prd> min_2 = cube.Center() - Point3<T,_Prd>(cube.Length(),cube.Depth(),cube.Height())/2.0;
    Point3<T,_Prd> max_2 = cube.Center() + Point3<T,_Prd>(cube.Length(),cube.Depth(),cube.Height())/2.0;

    if(Volume()<cube.Volume())
    {
        Vector3D::Swap(min_1,min_2);
        Vector3D::Swap(max_1,max_2);
    }

    if(min_1[0]<=min_2[0] && min_1[1]<=min_2[1] && min_1[2]<=min_2[2]
    && max_1[0]>=min_2[0] && max_1[1]>=min_2[1] && max_1[2]>=min_2[2])
        return true;

    if(min_1[0]<=max_2[0] && min_1[1]<=max_2[1] && min_1[2]<=max_2[2]
    && max_1[0]>=max_2[0] && max_1[1]>=max_2[1] && max_1[2]>=max_2[2])
        return true;

    return false;
};
like image 640
tomriddle_1234 Avatar asked Jun 18 '26 13:06

tomriddle_1234


1 Answers

One box collides with another if there is an intersecting range in all dimensions.

The intersection of range [a,b] with range [c,d] is [max(a,c),min(b,d)].

In the case of the ranges not intersecting, the result will be an invalid range, with the start of the range greater than the end of the range.

So the collision can be done like this:

bool collides(const Box &box1,const Box &box2)
{
  assert(box1.numberOfDimensions()==box2.numberOfDimensions());
  for (size_t i=0; i!=box1.numberOfDimensions(); ++i) {
    float a = max(box1.minForDimension(i),box2.minForDimension(i));
    float b = min(box1.maxForDimension(i),box2.maxForDimension(i));
    if (a>b) return false;
  }
  return true;
}
like image 148
Vaughn Cato Avatar answered Jun 21 '26 02:06

Vaughn Cato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!