2D/3D边界框碰撞检测有答案,但我的问题是如何将情况发展到多维(4D或更多)?
这是3D案例的代码。
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;
};
如果所有维度都有相交范围,则一个框与另一个框发生碰撞。
范围 [a,b] 与范围 [c,d] 的交集是 [max(a,c),min(b,d)]。
在范围不相交的情况下,结果将是无效范围,范围的开始大于范围的结束。
所以碰撞可以这样做:
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;
}