2017-10-14 96 views
-1
private void ingame_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Space) 
     { 
      bullet = new PictureBox(); 
      bullet.Image = WindowsFormsApplication1.Properties.Resources.bullet; 
      bullet.Size = new Size(8, 30); 
      bullet.Location = new Point(246, 364); 
      bullet.SizeMode = PictureBoxSizeMode.StretchImage; 
      bullet.BackColor = Color.Transparent; 

      this.Controls.Add(bullet); 

      this.SuspendLayout(); 
      bullet.Location = new Point(bullet.Location.X, bullet.Location.Y - 10); 
      this.ResumeLayout(); 
      timer1.Interval = 10; 
      timer1.Start(); 
     } 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     bullet.Location = new Point(bullet.Location.X, bullet.Location.Y-1); 
    } 

每一次在一次空格键点击一个新的子弹创建移动多个pictureboxes,但如果你有一颗子弹已经在屏幕上冻结,而新的移动。有没有办法让他们两个/更多的移动?在相同的变量名C#

+0

哪里是你的'bullet'变量实际上宣告?你的意思是保留一堆子弹而不是一个?像“列表”一样? – David

+0

如果你想跟踪多颗子弹,那么你需要一个集合。考虑一个'List '。有一些运气会发展成一个名单。 –

+0

谢谢,它只是在程序外面声明为“public PictureBox bullet;” – space482

回答

0

你有什么是PictureBox。你想要的是一个List<PictureBox>。例如:

public List<PictureBox> bullets = new List<PictureBox>(); 

(我会建议一个私有成员,甚至是属性,但只是为了保持最小的变化,从当前的代码,这应该是好的。)

首先,从删除您的定时器逻辑KeyDown事件并将其放在只执行一次的地方,如FormLoad。你只需要一个计时器滴答。

然后在您的KeyDown事件中,向列表中添加新的“项目符号”。事情是这样的:

if (e.KeyCode == Keys.Space) 
{ 
    // declare a local variable 
    var bullet = new PictureBox(); 

    // set the rest of the properties and add the control to the form like you normally do 

    // but also add it to the new class-level list: 
    bullets.Add(bullet); 
} 

然后在你的计时器滴答事件,只需通过列表循环:

foreach (var bullet in bullets) 
    bullet.Location = new Point(bullet.Location.X, bullet.Location.Y-1);