以下是對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