使用 PictureBox 的 C# 碰撞检测
C# Collision Detection with 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;
//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 是错误的,因为每次一个图片框不相交你添加新的框但另一个可能会相交,试试这样的事情:
bool pBDoIntersect;
foreach (Control picturebox in this.Controls)
{
if (PB.Bounds.IntersectsWith(picturebox.Bounds))
{
pBDoIntersect=true;
}
}
if(!pBDoIntersect)this.Controls.Add(PB);
我有一个程序可以在单击表单时添加一个图片框,但我想确保该图片框不与任何现有图片框重叠。
目前我有
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 是错误的,因为每次一个图片框不相交你添加新的框但另一个可能会相交,试试这样的事情:
bool pBDoIntersect;
foreach (Control picturebox in this.Controls)
{
if (PB.Bounds.IntersectsWith(picturebox.Bounds))
{
pBDoIntersect=true;
}
}
if(!pBDoIntersect)this.Controls.Add(PB);