'Problem with pictureboxes spawning and overlapping WINFORMS C#

I dont want the pictureboxes to spawn in each other or to overlap.



Solution 1:[1]

Here's how you can create a loop that picks a random location that doesn't intersect with any of your other existing enemies:

Rectangle rc1;
Rectangle rc2;
bool intersected;
do
{
    intersected = false;
    tempx = random.Next(1, 701);
    Gegner.Location = new Point(tempx, 12);
    rc1 = new Rectangle(Gegner.Location, Gegner.Size);
    foreach(PictureBox pb in gengerList)
    {
        rc2 = new Rectangle(pb.Location, pb.Size);
        if (rc1.IntersectsWith(rc2))
        {
            intersected = true;
            break;
        }
    }
} while (intersected);
// don't add new PB to list until AFTER 
//you've made sure it doesn't intersect with any others
gengerList.Add(Gegner); 

Note the comment at the bottom. Make sure you don't add the new PB to the List until AFTER you have made sure it doesn't intersect with of the other ones already there. If you add it beforehand then it will intersect with itself and get stuck in the loop.

If it still gets stuck then there is no way to place that number of PBs in the area you've specified, given the random locations they were placed. In that case, re-think the sizes and/or use a different method to place them.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1