我试图在画布的圆形区域中绘制各种不重叠的正方形。
最初,我试着在圆圈内的任意位置创建正方形,并检查它们是否重叠,但过了一段时间,我意识到这对于我所需要的东西来说效率太低、太复杂了。
我想要一个算法,使用圆心坐标,圆的半径,正方形网格的大小,并返回网格上每个正方形的位置的坐标数组,网格上的所有边缘都在圆环内。

最佳答案

我假设你希望圆中有未填充的空间,而不是用偏平方填充?如果是这样,有效的正方形将是那些所有四个角都在圆内的正方形,所以一个简单的循环将为您找到它们下面的代码应该可以做到这一点,尽管您可能希望在我将其拆分以获得清晰的结果时对其进行更多的压缩。

const size = 4; // The size of each square.
const squareCoords = []; // The top-left corners of each valid square.
const circle = [10, 10, 10]; // The circle, in the form [centerX, centerY, radius]

function DistanceSquared(x1, y1, x2, y2) {
    return (x2-x1) ** 2 + (y2-y1) ** 2;
}
function isInsideCircle(x, y, cx, cy, r) {
    return (DistanceSquared(x, y, cx, cy) <= r ** 2);
}

let topLeftInside = false, bottomRightInside = false, topRightInside = false, bottomLeftInside = false;
for (let xx = circle[0] - circle[2]; xx < circle[0] + circle[2]; xx += size) {
    for (let yy = circle[1] - circle[2]; yy < circle[1] + circle[2]; yy += size) {
        topLeftInside = isInsideCircle(xx, yy, circle[0], circle[1], circle[2]);
        bottomRightInside = isInsideCircle(xx + size, yy + size, circle[0], circle[1], circle[2]);
        bottomLeftInside = isInsideCircle(xx, yy + size, circle[0], circle[1], circle[2]);
        topRightInside = isInsideCircle(xx + size, yy, circle[0], circle[1], circle[2]);
        if (topLeftInside && bottomRightInside && bottomLeftInside && topRightInside) {
            squareCoords.push([xx, yy]);
        }
    }
}

10-05 20:51
查看更多