圆和矩形的交点代码不起作用?

时间:2019-06-09 08:59:53

标签: java geometry collision-detection bounds

为什么我的代码没有检测到圆形和矩形相交?

public static boolean RectCircleColliding(Circle circle, Rectangle rect)
{  
    double distX = Math.abs(circle.getCenterX() - rect.getX() - rect.getWidth()/2);
    double distY = Math.abs(circle.getCenterY() - rect.getY() - rect.getHeight()/2); 

    if (distX > rect.getWidth()/2 + circle.getRadius())
        return false;
    if (distY > rect.getHeight()/2 + circle.getRadius())
        return false;

    if (distX <= rect.getWidth()/2)
        return true;
    if (distY <= rect.getHeight()/2) 
        return true;

    double dx = distX - rect.getWidth()/2;
    double dy = distY - rect.getHeight()/2; 

    return dx*dx + dy*dy <= (circle.getRadius()*circle.getRadius());
}    

我使用以下圆形和矩形坐标:

Rectangle bounds = new Rectangle(7, 12, 2, 6);

Circle ball = new Circle(5, 7, 4.123);

1 个答案:

答案 0 :(得分:0)

您两次处理“距离”并引入错误。条件可以简化(用数据替换rect.center

dx = Max(Math.abs((circle.getCenterX() - rect.center.x) - rect.width / 2, 0);
dy = Max(Math.abs(circle.getCenterY() - rect.center.y) - rect.height / 2, 0);
return dx * dx + dy * dy <= (circle.getRadius()*circle.getRadius());