在我的 libgdx 游戏中,我有 3D BoundingBoxes 和 Spheres 用于地图和玩家对象。我想计算它们是否相互碰撞,以便正确模拟这些物体的运动。我可以使用什么方法来计算这些对象是否碰撞/相交?
问问题
4815 次
2 回答
4
您可以使用以下方法:
public static boolean intersectsWith(BoundingBox boundingBox, Sphere sphere) {
float dmin = 0;
Vector3 center = sphere.center;
Vector3 bmin = boundingBox.getMin();
Vector3 bmax = boundingBox.getMax();
if (center.x < bmin.x) {
dmin += Math.pow(center.x - bmin.x, 2);
} else if (center.x > bmax.x) {
dmin += Math.pow(center.x - bmax.x, 2);
}
if (center.y < bmin.y) {
dmin += Math.pow(center.y - bmin.y, 2);
} else if (center.y > bmax.y) {
dmin += Math.pow(center.y - bmax.y, 2);
}
if (center.z < bmin.z) {
dmin += Math.pow(center.z - bmin.z, 2);
} else if (center.z > bmax.z) {
dmin += Math.pow(center.z - bmax.z, 2);
}
return dmin <= Math.pow(sphere.radius, 2);
}
它仿照
一种简单的箱体相交测试方法,Jim Arvo 出自“Graphics Gems”,学术出版社,1990 年
可以在此处找到示例 C 代码:http ://www.realtimerendering.com/resources/GraphicsGems/gems/BoxSphere.c
于 2013-03-06T12:26:18.733 回答
2
上述答案仅适用于 AABB(Axis Aligned Bounding Box)。该方法虽然简洁而美观。所以我将它扩展为包括一般的边界框。Bellow 是提供与上述相同算法的最小代码。在下面的代码中,边界框由一个中心和 3 个方向向量 R、S 和 T 指定。每个向量代表框的主要边缘的方向和长度。
struct OBBox{
vector3 center;
vector3 S; // representing side s.
vector3 R;
vector3 T;
/* s, r, and t take -1 or +1 representing a corner along side S, R, and T correspondingly. If one of s, r, or t is 0 then middle of corresponding edge of the non-zero side is returned. If 2 of them are 0, then middle of the plane of the corresponding side is returned. */
vector3 getCorner(int s, int r, int t)
{
return center + ( s*S + r*R + t*T)/2.0;
}
}
public static boolean intersectsWith(OBBox bbox, Sphere sphere){
float dmin = 0.;
vector3 center = sphere.center;
float centerS = center.S;
float centerR = center.R;
float centerT = center.T;
vector3 bminS = bbox.getCorner(-1, 0, 0);
vector3 bmaxS = bbox.getCorner(1, 0, 0);
vector3 bminR = bbox.getCorner(0, -1, 0);
vector3 bmaxR = bbox.getCorner(0, 1, 0);
vector3 bminT = bbox.getCorner(0, 0, -1);
vector3 bmaxT = bbox.getCorner(0, 0, 1);
if(centerS < bminS.S) {
dmin += (centerS-bminS).(centerS-minS); // . means 3d dot product.
else if(centerS > bmaxS)
dmin += (centerS-bmaxS).(centerS-bmaxS);
}
if(centerR < bminR.R) {
dmin += (centerR-bminR).(centerR-minR);
else if(centerR > bmaxR.R)
dmin += (centerR-bmaxR).(centerR-bmaxR);
}
if(centerT < bminT.T) {
dmin += (centerT-bminT).(centerT-minT);
else if(centerT > bmaxT)
dmin += (centerT-bmaxT).(centerT-bmaxT);
}
return dmin <= (sphere.radius).(sphere.radius);
}
于 2015-06-04T07:32:47.010 回答