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