I am having trouble spawning shapes in SFML in Codeblocks and verifying if its overlapping another shape and if it is indeed overlapping then trying to spawn it again in another position.
Here is the code:
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;
}
}
}
If i use a while instead of a if statement if will enter an infinite cycle.
Is there anyway i can make this work?
Thank you so much for your time :D
To check if the currently spawned shape doesn't intersect with any of the already spawned, your nested loop needs to iterate from the first to the previously spawned shape, so from the index 0
to the previous spawning index i - 1
, not start from the previous. In case of overlapping, you also need to reset the inner loop index j = 0;
, to make sure that the new position doesn't cause overlapping with already checked shapes.
There is no need to initialize the current shape while checking intersections with previous shapes. I moved those instructions to the outer loop, so they are called once for every new shape.
There is also no need to initialize the random number generator more than once. I removed the second srand(time(0));
.
The rest is unchanged.
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;
}
}
}