views:

142

answers:

3

Hey, I am making a frogger type game and I am using a timer to make the images move across the screen. I am also using the keydown event to handle when the user moves the 'frog'. So, w moved up, s moves down etc.

The problem I have come across is that whenever the user presses any movement button, the timer freezes. This means if the user just holds down 'w' or up, all the cars stop moving.

Is there a way of putting the timer in a background worker or a way to make the timer carry on ticking even when the user is moving?

Thanks for any help!

This is what I currently have:

    public string i;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyValue == 68)
        {
            i = "right";
            backgroundWorker1.RunWorkerAsync();
        }
    }


private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        if (i == "right")
        {
            pictureBox1.Location = new Point((pictureBox1.Location.X + 17), pictureBox1.Location.Y);
        }
     }
+2  A: 

A background thread or worker is the solution. Here is a simple background worker.

        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.RunWorkerAsync();
    }


    static Timer _t;
    static void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        _t = new Timer();
        _t.Start();
    }
sadboy
Thanks for your help i'll give this a go
Crazyd22
Hope it helps. Also it might depend on what thread your drawing and processing code is handled, if you are processing things right in the keydown event on the ui thread it might be blocking there.
sadboy
@Sadboy: Make sure not to use the WinForms event driven Timer Component...
tommieb75
@tommieb75 yean, good point.
sadboy
A: 

You need to implement a thread to run in the background that keeps track of the timer or use a Backgroundworker class to do this for you. If you want precision Timer, use the System.Threading.Timer class.

Hope this helps, Best regards, Tom.

tommieb75
+1  A: 

Look at the Output window when you run your program with the debugger. You'll see lots of IllegalOperationException messages. The background worker method is dying on an exception, you are not noticing it because you don't check the e.Error property in a DoWorkCompleted event handler. That's why it ain't moving.

You are not allowed to set the properties of a control in a background thread. That's what the exception is trying to tell you. You'll need to give up on the idea of using threads to implement your UI logic. Games are usually implemented with a game loop.

Hans Passant
Thanks for your help!
Crazyd22