C#使用PictureBox进行碰撞检测
我有一个程序,在表单中单击时添加一个picturebox,但我想确保picturebox不会与任何现有picturebox重叠 目前我有C#使用PictureBox进行碰撞检测,c#,picturebox,collision,C#,Picturebox,Collision,我有一个程序,在表单中单击时添加一个picturebox,但我想确保picturebox不会与任何现有picturebox重叠 目前我有 PictureBox PB = new PictureBox(); PB.Name = "Table " + number; PB.BackgroundImage = Image.FromFile("C:\\table.png"); PB.Size = new Size(65,65); //x = x + 70; //
PictureBox PB = new PictureBox();
PB.Name = "Table " + number;
PB.BackgroundImage = Image.FromFile("C:\\table.png");
PB.Size = new Size(65,65);
//x = x + 70;
//y = y + 50;
PB.Location = new Point(LocX, LocY);
PB.MouseDoubleClick += new MouseEventHandler(this.PB_DoubleClick);
foreach (Control picturebox in this.Controls)
{
if (PB.Bounds.IntersectsWith(picturebox.Bounds))
{
//Collision
}
else
{
this.Controls.Add(PB);
}
}
但是,这些控件仍然可以相互重叠,请参见:
很明显,代码中有一些我没有做的事情,但我看不出是什么?您的foreach是错误的,因为每当一个picturebox没有相交时,您都会添加一个新的框,但另一个框可能会这样做,请尝试以下操作:
bool pBDoIntersect;
foreach (Control picturebox in this.Controls)
{
if (PB.Bounds.IntersectsWith(picturebox.Bounds))
{
pBDoIntersect=true;
}
}
if(!pBDoIntersect)this.Controls.Add(PB);
我建议你解释一下OP为什么不起作用,以及你的答案是如何解决的。谢谢你的回答!当我运行您的更改时,它不允许我单击表单上的任何位置?除此之外,我相信这是因为如果我在现有项的范围内单击,bool将设置为持续true,但是如果我使用else重置它,它将返回到我的原始问题?你说的不允许是什么意思?如果您多次使用它,则在添加PictureBox后必须将bool设置为false,您将此代码放在哪里?您希望这种情况在设计时发生,还是在运行时发生?