我試圖為學校專案制作一個小型太空入侵者型別的游戲。到目前為止,我對自己所做的一切感到非常滿意,但現在我正在與敵人的生成作斗爭。我不希望圖片框相互生成或重疊。
public void Gegnerspawn()
{
int tempx = 1;
for (int x = 0; x <= 5; x )
{
Random random = new Random();
tempx = random.Next(1, 701);
PictureBox Gegner = new PictureBox();
Gegnerlist.Add(Gegner);
Gegnerlist[x].Image = Properties.Resources.enemy;
Gegnerlist[x].SizeMode = PictureBoxSizeMode.StretchImage;
Gegnerlist[x].Tag = "Gegner";
Gegnerlist[x].BackColor = Color.Transparent;
Gegnerlist[x].Size = new Size(50, 50);
foreach(int xcoords in xcordlist)
{
//if (xcoords 50 >= tempx && xcoords - 50 <= tempx)
//{
//}
//else
//{
//tempx = random.Next(1, 701);
//}
while(tempx >= xcoords && tempx <= xcoords 50 || tempx 50 >= xcoords && tempx 50 <= xcoords 50) //tempx >= xcoords && xcoords 50 <= tempx
{
tempx = random.Next(1, 701);
}
}
xcordlist.Add(tempx);
Console.WriteLine(tempx);
Gegnerlist[x].Location = new Point(tempx, 12);
this.Controls.Add(Gegnerlist[x]);
Gegnerlist[x].BringToFront();
}
}
對不起變數名。謝謝!
uj5u.com熱心網友回復:
以下是如何創建一個回圈,選擇一個不與任何其他現有敵人相交的隨機位置:
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);
注意底部的注釋。確保在確保它不與已經存在的其他 PB 相交之前,不要將新的 PB 添加到串列中。如果您事先添加它,那么它將與自身相交并卡在回圈中。
如果它仍然卡住,那么考慮到它們放置的隨機位置,就無法在您指定的區域中放置該數量的 PB。在這種情況下,請重新考慮尺寸和/或使用不同的方法來放置它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450358.html
