為了學習,當然為了好玩,我正在構建一個模仿蛇,唯一的區別應該是地圖上出現了很多敵人或物體,而不是無盡的鏈條,并且游戲應該變得越來越困難。
代碼片段應該顯示我如何創建我的控制元件,但我的問題是只有最后一個創建的控制元件實際上被我的“IntersectsWith”捕獲,在此之前創建的所有控制元件以及第一個控制元件都沒有對于我和我的球員來說,任何對手都不再是他們了。
這樣做的最佳方法是什么,以便可以在一個定義下找到所有創建的物件,這樣我就不必撰寫數百個 IntersectsWith If 陳述句。
我想學習如何動態創建控制元件并動態地直接訪問它們,我的玩家可以通過碰撞與它們進行互動。
我真的以為我可以使用隨機字符生成器來解決這個問題,并且不同的控制元件名稱可以解決這個問題,但是唉 - 這不是現實^^
Random rnd = new Random();
PictureBox Enemy = new PictureBox();
private async void timer1_Tick(object sender, EventArgs e)
{
if (Person.Bounds.IntersectsWith(Food.Bounds))
{
int ascii_index2 = rnd.Next(97, 123);
char char1 = Convert.ToChar(ascii_index2);
char char2 = Convert.ToChar(ascii_index2);
string myletter = Convert.ToString(char1) Convert.ToString(char2);
Enemy = new PictureBox
{
Location = new Point(rnd.Next(20, playground.Right - 20), rnd.Next(20, playground.Bottom - 20)),
Name = "Enemy" myletter,
Size = new Size(24,24),
BackColor = Color.Red,
};
this.Controls.Add(Enemy);
Enemy.BringToFront();
Food.Location = new Point(rnd.Next(20, playground.Right - 20), rnd.Next(20, playground.Bottom - 20));
score ;
lbScore.Text = "Score: " score.ToString();
}
if(Person.Bounds.IntersectsWith(Enemy.Bounds))
{
timer1.Stop();
}
if (Person.Left <= playground.Left && !changed)
{
Person.Location = new Point(playground.Right, Person.Location.Y);
changed = true;
}
else
if (Person.Right >= playground.Right && !changed)
{
Person.Location = new Point(playground.Left, Person.Location.Y);
changed = true;
}
else
if (Person.Top <= playground.Top && !changed)
{
Person.Location = new Point(Person.Location.X, playground.Bottom);
changed = true;
}
else
if (Person.Bottom >= playground.Bottom && !changed)
{
Person.Location = new Point(Person.Location.X, playground.Top);
changed = true;
}
這是我所擁有的圖片: Player = BlackDot,Food = GreenDot,Enemy = RedDot 它會按照您單擊的方向自動移動,如果您按住鍵,您可以更快地移動。移動鍵:W、A、S、D

uj5u.com熱心網友回復:
您需要創建一個串列并將所有創建的敵人存盤在其中。
首先,您需要創建一個串列:
List<PictureBox> enemyList = new List<PictureBox>();
在你創建了一個新的敵人之后,將它添加到你的串列中
Enemy = new PictureBox{};
enemieList.add(Enemy);
因為那時您可以檢查此串列中的每個 PictureBox 以及它是否與您的播放器相交。
foreach(PictureBox p in enemyList)
{
if(Person.Bounds.IntersectsWith(p.Bounds))
{
timer1.Stop();
}
}
那將是我對您問題的快速解決方案。
uj5u.com熱心網友回復:
假設這Person是您的播放器,而不是typeenemy欄位,而是 type欄位。然后,您將每個新敵人添加到該串列中,然后您可以執行以下操作:PictureBoxenemiesList<PictureBox>PictureBox
if (enemies.Any(enemy => person.Bounds.IntersectsWith(enemy.Bounds))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482431.html
