您需要的是能够确定边界框之间的交叉点和距离。假设您有轴对齐的边界框(AABB,即矩形框边平行于轴),您可以将 2D 计算减少为 1D 间隔关系——分别计算 x 和 y 间隔之间的关系并将它们组合起来。这种分而治之的策略应该大大简化逻辑。
这是一个可以用作起点的类。它未经测试,不应用于生产代码——我知道它不适用于特殊情况,例如空间隔(min > max)或单例间隔(min == max)——但它应该可以帮助你获得在你的路上。
package stackoverflow;
public enum IntervalRelation
{
LEFT,
LEFT_TOUCHING,
OVERLAP_LEFT,
CONTAINING,
CONTAINED,
OVERLAP_RIGHT,
RIGHT_TOUCHING,
RIGHT;
public static double getIntervalDistance(
double min1, double max1,
double min2, double max2) {
double maxOfMin = Math.max(min1, min2);
double minOfMax = Math.min(max1, max2);
return maxOfMin - minOfMax;
}
public static IntervalRelation between(
double min1, double max1,
double min2, double max2) {
double dist = getIntervalDistance(min1, max1, min2, max2);
if (dist > 0) {
// not touching or intersecting
return min1 < min2? LEFT : RIGHT;
} else if (dist == 0) {
// touching
return min1 < min2? LEFT_TOUCHING : RIGHT_TOUCHING;
} else {
// overlapping or containment
if (min1 < min2) {
// overlap left or containing
return max1 < max2? OVERLAP_LEFT : CONTAINING;
} else {
return max1 < max2? CONTAINED : OVERLAP_RIGHT;
}
}
}
public static void main(String[] args) {
System.out.println(between( 0.0,+1.0, -2.0,-1.0));
System.out.println(between( 0.0,+1.0, +2.0,+3.0));
System.out.println(between( 0.0,+1.0, -2.0,+0.0));
System.out.println(between( 0.0,+1.0, +1.0,+3.0));
System.out.println(between( 0.0,+1.0, +0.5,+1.5));
System.out.println(between( 0.0,+1.0, -0.5,+0.5));
System.out.println(between( 0.0,+1.0, -0.5,+1.5));
System.out.println(between( 0.0,+1.0, +0.5,+0.6));
}
}
总的来说,我发现提供类而不是总是必须提供最小/最大参数对并且必须检查空虚或单例非常有用。Interval