gpt4 book ai didi

javascript - 如何在圆形网格内找到特定大小的所有正方形

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:07:56 24 4
gpt4 key购买 nike

我正在尝试在 Canvas 的圆形区域中绘制各种不重叠的正方形。

最初我尝试在圆内的随机位置创建正方形并检查它们是否重叠,但一段时间后我意识到它对于我需要的东西来说效率太低且太复杂。

我想要一个算法,它使用圆心坐标、圆半径和正方形网格的大小,并为具有所有边的网格上每个正方形的位置返回一个坐标数组圈内。

最佳答案

我假设您希望圆圈中有未填充的空间而不是用部分正方形填充它?如果是这样,有效的正方形将是所有四个 Angular 都在圆内的正方形,因此一个简单的循环将为您找到它们。下面的代码应该可以做到这一点,但为了清楚起见,我已将其拆分,您可能希望将其压缩得更多。

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]);
}
}
}

关于javascript - 如何在圆形网格内找到特定大小的所有正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54009150/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com