C#picturebox和计时器

时间:2014-05-27 10:39:35

标签: c# timer picturebox

我正在尝试使用图片框和计时器创建一款汽车游戏

这是我的代码

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    PictureBox car = new PictureBox();
    Timer t = new Timer();

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        //Right arrow key
        if (e.KeyCode.Equals(Keys.Right) && carPlayer.Location.X < 300)
        {
            int x = carPlayer.Location.X + 5;
            int y = carPlayer.Location.Y;
            int width = carPlayer.Size.Width;
            int height = carPlayer.Size.Height;
            carPlayer.SetBounds(x, y, width, height);
        }

        //Left arrow key
        if (e.KeyCode.Equals(Keys.Left) && carPlayer.Location.X > 35)
        {
            int x = carPlayer.Location.X - 5;
            int y = carPlayer.Location.Y;
            int width = carPlayer.Size.Width;
            int height = carPlayer.Size.Height;
            carPlayer.SetBounds(x, y, width, height);
        }

        if (e.KeyCode.Equals(Keys.Space))
        {
            spawnCar();
        }
    }


    void spawnCar()
    {
        string[] cars = { "data/car_red.png", "data/car_blue.png", "data/car_green.png", "data/car_grey.png" };
        Random rand = new Random();
        car.SizeMode = PictureBoxSizeMode.StretchImage;
        car.Image = Image.FromFile(cars[rand.Next(0, 4)]);
        car.Visible = true;

        if (rand.Next(0,2) == 0)
        {
            car.SetBounds(100, 10, 50, 85);
        }
        else
        {
            car.SetBounds(250, 10, 50, 85);
        }

        this.Controls.Add(car);
        car.BringToFront();

        t.Interval = 1;
        t.Tick += new EventHandler(t_Tick);
        t.Start();
    }

    private void t_Tick(object sender, EventArgs e)
    {
        if (car.Bounds.IntersectsWith(carPlayer.Bounds))
        {
            t.Stop();
            car.Image = Image.FromFile("data/car_wreck.png");
            carPlayer.Image = Image.FromFile("data/player_wreck.png");
        }
        if (car.Bounds.Y > 340)
        {
            t.Stop();
            this.Controls.Remove(car);
        }
        else
        {
            car.Top++;
        }
    }
}

http://i.stack.imgur.com/NhCgY.png

现在,当我按下空间时,汽车出现在顶部并缓慢向下移动并在到达底部时消失但是当我多次按空间时,汽车的速度变得越来越快。 任何人都可以帮助我让汽车每次创建都以相同的速度移动。

由于

1 个答案:

答案 0 :(得分:2)

问题是你要为每个汽车产生一个新的Tick事件处理程序,你只想这样做一次。但是,没有一种简单的方法来检查是否已经分配了处理程序,所以我建议使用全局标记...

//at class level
bool eventSet = false;

//in spawn method
t.Interval = 1;
if(!eventSet)//check if no handler assigned yet
{
    t.Tick += new EventHandler(t_Tick);
    eventSet = true;
}
t.Start();

或者,您可以在分配...

之前尝试删除处理程序
//in spawn method
t.Interval = 1;
t.Tick -= new EventHandler(t_Tick);//remove previous one if it exists
t.Tick += new EventHandler(t_Tick);
t.Start();