我需要找到一种算法来确定正方形和矩形之间的关系。它必须能够确定:
- 正方形完全在长方形里面
- 正方形部分位于(重叠)矩形内
- 正方形的角只与矩形的角相交
- 正方形的边在长方形的边上
这里是输入(给定值),可帮助我们为每种情况提取数学公式:
- 正方形中心的x坐标= squareX
- 正方形中心的y坐标= squareY
- 正方形的宽度 = squareW
- 矩形中心的x坐标=recX
- 矩形中心的y坐标= recY
- 矩形的宽度 = recW
- 矩形的长度 = recL
P.S:矩形的尺寸总是大于正方形的宽度。
一旦我们可以使用数学运算提取算法,我就会用 Java 编写代码。
编辑:
对于接触角的情况,这是我写的代码,它有效(Math.abs 表示绝对值):
((Math.abs(Math.abs(recX-squareX)-(recW+squareW)/2))<=0.001) && ((Math.abs(Math.abs(recY-squareY)-(recL+squareW)/2))<=0.001)
最佳答案
double 更新
double dx = Math.abs(rectX - squareX);
double dy = Math.abs(rectY - squarey);
double dw2 = (rectW + squareW) / 2;
double dh2 = (rectL + squareW) / 2;
if (Double.compare(dx, dw2) == 0 && Double.compare(dy, dh2) == 0)
return CORNER_TOUCH;
else if (Double.compare(dx, dw2) > 0 || Double.compare(dy, dh2) > 0)
return OUTSIDE;
else if (Double.compare(dx, dw2) == 0 || Double.compare(dy, dh2) == 0)
return EDGE_TOUCH;
else if (Double.compare(dx, rectW - dw2) <= 0 &&
Double.compare(dy, rectL - dh2) <= 0)
return INSIDE;
else
return OVERLAPS;
关于java - 确定正方形和矩形之间关系的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4906038/