geometry - 2D 圆形和矩形相交测试

标签 geometry collision-detection

我正在做的是测试圆形和矩形之间的相交程度。我想知道矩形是否完全在圆内,部分相交,或者根本没有相交。

我附上了今天编写的代码,它只是检查从圆心到矩形角的距离以确定相交的级别。

我想知道是否有更有效的方法来做到这一点?

编辑: 这是我更新后的工作代码。 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;
    }

最佳答案

我认为您的代码没有考虑这些交叉点:

enter image description here

一旦您增强了代码/问题,我就会删除此答案。

关于geometry - 2D 圆形和矩形相交测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7548696/

相关文章:

java - 处理冲突 - 数组查找成本高昂

c++ - 碰撞响应 (SAT) 问题

绘制具有/不同重叠边框的矩形边框的算法

math - 任意旋转中两条抛物线相交的代码或公式

sql - 如何通过 STWithin 对 SQL Server 几何数据进行分组?

c# - 分离两个碰撞的圆圈

graphics - 如何测试线段是否与二维轴对齐矩形相交?

c++ - C++ 中的射线网格交集或 AABB 树实现,开销很小?

c# - 使用 PNG 作为带碰撞检测的背景图

Javascript:检测碰撞的 div