SFML 如何产生随机形状而不让它与另一个形状重叠

SFML How to spawn random shape and not have it overlap with another shape

我在 Codeblocks 的 SFML 中生成形状并验证它是否与另一个形状重叠以及是否确实重叠然后尝试在另一个位置再次生成它时遇到问题。

代码如下:

srand(time(0));
CircleShape circleObjectArray[50];

for(int i = 0; i < 50; i++)
{
    for(int j = i - 1; j < 49; j++)
    {
    circleObjectArray[i] = CircleShape(rand() % 50 + 5);
    circleObjectArray[i].setPosition(rand() % 1870 + 50, rand() % 1030 + 50);
    circleObjectArray[i].setFillColor(Color(rand() % 255,rand() % 255,rand() % 255));
    if(circleObjectArray[i].getGlobalBounds().intersects( circleObjectArray[j].getGlobalBounds()))
    {
        srand(time(0));
        circleObjectArray[i].setPosition(rand() % 1870 + 50, rand() % 1030 + 50);
        cout << "overlap" << endl;
    }
    }
}

如果我使用 while 而不是 if 语句 if 将进入无限循环。

有什么办法可以让这个工作吗?

非常感谢您的宝贵时间:D

要检查当前生成的形状是否与任何已生成的形状不相交,您的嵌套循环需要从第一个迭代到先前生成的形状,因此从索引 0 到前一个产卵指数i - 1,不是从上一个开始的。在重叠的情况下,您还需要重置内部循环索引 j = 0;,以确保新位置不会导致与已检查的形状重叠。

检查与先前形状的交点时无需初始化当前形状。我将这些指令移到了外循环,因此每个新形状都会调用一次。

也不需要多次初始化随机数生成器。我删除了第二个 srand(time(0));.

其余不变

srand(time(0));
CircleShape circleObjectArray[50];

for (int i = 0; i < 50; i++)
{
    circleObjectArray[i] = CircleShape(rand() % 50 + 5);
    circleObjectArray[i].setPosition(rand() % 1870 + 50, rand() % 1030 + 50);
    circleObjectArray[i].setFillColor(Color(rand() % 255, rand() % 255, rand() % 255));

    for (int j = 0; j < i - 1; j++)
    {
        if (circleObjectArray[i].getGlobalBounds().intersects(circleObjectArray[j].getGlobalBounds()))
        {
            circleObjectArray[i].setPosition(rand() % 1870 + 50, rand() % 1030 + 50);
            cout << "overlap" << endl;
            j = 0;
        }
    }
}