所以我為一個學校專案用windows表單制作了一個游戲。唯一的問題是,我的圖片相互重疊。所以我的問題是如何將它們全部放在不相互接觸或不重疊的不同位置?
在這個方法中,我創建了僵尸,在這里我只是在 x-as 上選擇 -100 到 0 之間的隨機位置
public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
for (int i = 0; i < aantal; i )
{
PictureBox picture = new PictureBox();
picture.Image = Properties.Resources.ZombieDik;
picture.Size = new Size(200, 200);
picture.Location = new Point(random.Next(1500), random.Next(-100,0));
picture.SizeMode = PictureBoxSizeMode.Zoom;
picture.Click = zombie_Click;
picture.BackColor = Color.Transparent;
formInstance.Controls.Add(picture);
picture.Tag = zombies[i];
}
}
僵尸重疊的圖片
uj5u.com熱心網友回復:
跟蹤已經放置的圖片框,并驗證邊界是否會重疊。
//List of all pictureBoxes
private List<PictureBox> _pictureBoxes = new List<PictureBox>();
public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
for (int i = 0; i < aantal; i )
{
Rectangle newPosition;
//loop till you found a new position
while (true)
{
var newPoint = new Point(random.Next(1500), random.Next(-100,0));
var newSize = new Size(200, 200);
newPosition = new Rectangle(newPoint, newSize);
//validate the newPosition
if (!_pictureBoxes.Any(x => x.Bounds.IntersectsWith(newPosition)))
{
//break the loop when there isn't an overlapping rectangle found
break;
}
}
PictureBox picture = new PictureBox();
_pictureBoxes.Add(newPosition);
picture.Image = Properties.Resources.ZombieDik;
picture.Size = newPosition.Size;
picture.Location = newPosition.Location;
...
}
}
為了驗證重疊我正在使用類的IntersectWith方法Rectangle
https://docs.microsoft.com/en-us/dotnet/api/system.drawing.rectangle.intersectswith?view=net-6.0#system-drawing-rectangle-intersectswith(system-drawing-rectangle)
uj5u.com熱心網友回復:
我修復了您的代碼,因此圖片框不會相互重疊:
public void ZombieMaker(int aantal, Form formInstance, string ZombieDik)
{
for (int i = 0; i < aantal; i )
{
PictureBox picture = new PictureBox();
picture.Image = Properties.Resources.ZombieDik;
picture.Size = new Size(200, 200);
picture.Location = new Point(picture.Width * i, random.Next(-100,0));
picture.SizeMode = PictureBoxSizeMode.Zoom;
picture.Click = zombie_Click;
picture.BackColor = Color.Transparent;
formInstance.Controls.Add(picture);
picture.Tag = zombies[i];
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415668.html
標籤:
上一篇:一個位元組中的一個字母?C#
