一次移动多个图片框的同一个变量名C#

时间:2017-10-14 18:19:01

标签: c# animation

    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);
    }

每次单击空格键时都会创建一个新的项目符号,但是如果屏幕上已有项目符号,则它会冻结并且新项目会移动。有没有办法让他们两个/更多移动?

1 个答案:

答案 0 :(得分:1)

你拥有的是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);
相关问题