试图阻止随机生成的图片框不相互交叉
Trying to stop randomly generated pic boxes to not intersect with each other
我正在开发一个 windows 形式的程序,可以生成随机坐标点来画鱼。我需要鱼停止相互交叉,但我编写的代码不起作用。生成的坐标应放入矩形中,然后对照所有其他点矩形进行检查。鱼不断相交。知道为什么吗?
Code I wrote to stop the intersection.
for (int i = 0; i < fishNumber; i++)
{
// Checks for overlapping
fishX = x.Next(200, 3100);
fishY = y.Next(100, 1620);
fishPoints.Add(new Point(fishX, fishY));
for (int j = 0; j < i; j++)
{
while (i != 0 && new Rectangle(fishPoints[i], new Size(200, 134)).IntersectsWith(new Rectangle(fishPoints[j], new Size(200, 134))))
{
fishPoints.RemoveAt(i);
fishX = x.Next(200, 3100);
fishY = y.Next(100, 1620);
fishPoints.Add(new Point(fishX, fishY));
}
}
}
尝试更像下面的东西。它只会在确定它不与任何其他鱼相交后添加点:
Size fishSize = new Size(200, 134);
for (int i = 0; i < fishNumber;i++)
{
Point pt;
bool collided;
do
{
collided = false;
pt = new Point(x.Next(200, 3100), y.Next(100, 1620));
Rectangle rcNewFish = new Rectangle(pt, fishSize);
foreach(Point otherPt in fishPoints)
{
if (rcNewFish.IntersectsWith(new Rectangle(otherPt, fishSize)))
{
collided = true;
break;
}
}
} while (collided);
fishPoints.Add(pt);
}
我正在开发一个 windows 形式的程序,可以生成随机坐标点来画鱼。我需要鱼停止相互交叉,但我编写的代码不起作用。生成的坐标应放入矩形中,然后对照所有其他点矩形进行检查。鱼不断相交。知道为什么吗? Code I wrote to stop the intersection.
for (int i = 0; i < fishNumber; i++)
{
// Checks for overlapping
fishX = x.Next(200, 3100);
fishY = y.Next(100, 1620);
fishPoints.Add(new Point(fishX, fishY));
for (int j = 0; j < i; j++)
{
while (i != 0 && new Rectangle(fishPoints[i], new Size(200, 134)).IntersectsWith(new Rectangle(fishPoints[j], new Size(200, 134))))
{
fishPoints.RemoveAt(i);
fishX = x.Next(200, 3100);
fishY = y.Next(100, 1620);
fishPoints.Add(new Point(fishX, fishY));
}
}
}
尝试更像下面的东西。它只会在确定它不与任何其他鱼相交后添加点:
Size fishSize = new Size(200, 134);
for (int i = 0; i < fishNumber;i++)
{
Point pt;
bool collided;
do
{
collided = false;
pt = new Point(x.Next(200, 3100), y.Next(100, 1620));
Rectangle rcNewFish = new Rectangle(pt, fishSize);
foreach(Point otherPt in fishPoints)
{
if (rcNewFish.IntersectsWith(new Rectangle(otherPt, fishSize)))
{
collided = true;
break;
}
}
} while (collided);
fishPoints.Add(pt);
}