以下是对cartesian
轴的回答,其中(0, 0)
位于左下角。
编辑 由于您的x, y
是正方形的左上角。变换他们在中心:
圈
x = x+r
y = y-r
公式是x^2 + y^2 = r^2
,现在给点{x, y}
将内或圆上撒谎IFF x^ + y^2 <= r^2
时。现在,我们可以安全地假设,如果所有四个角点位于圆内或圆上,矩形将位于圆内。使用上述假设伪码为如果矩形包含在圆发现:
boolean contains(Circle c) {
Point p_rect_1 = {x, y};
Point p_rect_2 = {x + width, y };
Point p_rect_3 = {x + width, y + height };
Point p_rect_4 = {x, y + height };
Point[] points = new Point[] { p_rect_1, p_rect_2, p_rect_3, p_rect_4 };
foreach(Point p : points) {
// ** is raise to power
if ((c.x - p.x)**2 + (c.y - p.y)**2 > c.r**2) {
return false;
}
}
return true;
}
EDIT 进行计算(在下面的评论由吉姆建议的)更优化的方法是通过从计算矩形的最最远的角落圆的中心:
dx = max(centerX - rectLeft, rectRight - centerX);
dy = max(centerY - rectTop, rectBottom - centerY);
return radius*radius >= dx*dx + dy*dy
@Codeguy多少代码,您有WRI到目前为止解决它? – vikiiii