[英]Problem with pictureboxes spawning and overlapping WINFORMS C#
我不希望圖片框相互產生或重疊。
以下是如何創建一個循環,該循環選擇一個不與任何其他現有敵人相交的隨機位置:
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 添加到列表中。 如果您事先添加它,那么它會與自身相交並卡在循環中。
如果它仍然卡住,那么就無法在您指定的區域中放置該數量的 PB,因為它們的放置位置是隨機的。 在這種情況下,重新考慮尺寸和/或使用不同的方法來放置它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.