我正在做的是测试圆形和矩形之间的相交程度。我想知道矩形是否完全在圆内,部分相交,或者根本没有相交。
我附上了今天编写的代码,它只是检查从圆心到矩形角的距离以确定相交的级别。
我想知道是否有更有效的方法来做到这一点?
编辑: 这是我更新后的工作代码。 fullIntersect 是我自己的,我在 Circle-Rectangle collision detection (intersection) 上找到了partialIntersect 片段。我将对此保持开放状态,因为我仍然很好奇是否有更好的方法来做到这一点。
public boolean fullIntersect(float circleX, float circleY, float radius)
{
float radsq = radius * radius;
double xsq = Math.pow(circleX - xPosition, 2);
double xpwsq = Math.pow(circleX - (xPosition + width), 2);
double ysq = Math.pow(circleY - yPosition, 2);
double yphsq = Math.pow(circleY - (yPosition + height), 2);
if(xsq + ysq > radsq || xsq + yphsq > radsq || xpwsq + yphsq > radsq || xpwsq + ysq > radsq)
return false;
return true;
/* this is what the one if statement does
double disBotLeft = xsq + ysq;
double disTopLeft = xsq + yphsq;
double disTopRight = xpwsq + yphsq;
double disBotRight = xpwsq + ysq;
if(disBotRight > radsq) return false;
if(disBotLeft > radsq) return false;
if(disTopLeft > radsq) return false;
if(disTopRight > radsq) return false;
return true;
*/
}
public int intersects(float circleX, float circleY, float radius)
{
if(!enabled) return 0;
double wo2 = width / 2.0d;
double ho2 = height / 2.0d;
double circleDistanceX = Math.abs(circleX - xPosition - wo2);
double circleDistanceY = Math.abs(circleY - yPosition - ho2);
if (circleDistanceX > (wo2 + radius)) { return 0; }
if (circleDistanceY > (ho2 + radius)) { return 0; }
if(fullIntersect(circleX, circleY, radius)) { return 2; }
if (circleDistanceX <= (wo2)) { return 1; }
if (circleDistanceY <= (ho2)) { return 1; }
double cornerDistance_sq = Math.pow(circleDistanceX - wo2,2) +
Math.pow(circleDistanceY - ho2,2);
return cornerDistance_sq <= (radius*radius) ? 1 : 0;
}
最佳答案
我认为您的代码没有考虑这些交叉点:
一旦您增强了代码/问题,我就会删除此答案。
关于geometry - 2D 圆形和矩形相交测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7548696/