【问题标题】:SFML How to spawn random shape and not have it overlap with another shapeSFML 如何生成随机形状而不使其与另一个形状重叠
【发布时间】:2020-12-30 07:13:23
【问题描述】:

我在代码块中的 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

【问题讨论】:

    标签: c++ codeblocks sfml


    【解决方案1】:

    要检查当前生成的形状是否与任何已生成的形状不相交,您的嵌套循环需要从第一个形状迭代到先前生成的形状,因此从索引 0 到上一个生成索引 @987654322 @,不是从前面开始的。在重叠的情况下,您还需要重置内循环索引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;
            }
        }
    }
    

    【讨论】:

    • 非常感谢它成功了 :D 我只需要更改一下 if
    • @AndréSousa 对答案添加了重要的更正。如果发生重叠,您还需要重置内循环索引j = 0;,以确保新位置不会与已检查的形状重叠。
    猜你喜欢
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多