3

I am trying to make a Snake game. And what I want to happen is that each time the snake eats a piece of food it moves quicker.

I want to do this by making the timer tick faster.

I start the timer at an interval time of:

gltimer.Interval = new TimeSpan(20000)

And update it with:

public void updateTimer(object sender, EventArgs e)
{
    long nrTicks = gltimer.Interval.Ticks;
    nrTicks = (long)(nrTicks * 0.95);
    gltimer.Interval = new TimeSpan(nrTicks);
}

But when I run my game the speed stays the same until I reach the 14th snack and then it suddenly changes. I already figured out that the nrTicks then drops below 10000.

My question is why the Interval doesn't update for the intermediate values?

Bizhan
  • 16,157
  • 9
  • 63
  • 101
BVerspeek
  • 43
  • 3

1 Answers1

3

The DispatcherTimer is not designed to execute an action at precise intervals.

While it dispatches the action at the exact interval, the dispatched actions will get executed, when the GUI thread in your case the wpf application loop decides to do so.

You setting the interval to 20.000 ticks results in an interval of 20.000*100ns = 2.000.000ns = 2ms. A wpf application has a resolution of around 10ms at best.

Look at those posts:

Community
  • 1
  • 1
Gerald Degeneve
  • 547
  • 2
  • 8
  • Thank you for the information, but it doesn't quite answer my question. I'm starting it at a 2ms timer, and it runs (not quite that fast though so I see your point of the 10ms at best) and then try to shorten that time every time my snake eats something. But as soon as the value hits 1ms it suddenly speeds up instead of at each interval change I make beforehand. That is the behavior I don't understand. Also can you make recommendations for which kind of timer would be better suited for my needs? – BVerspeek May 18 '14 at 15:46
  • You can use a dispatcher timer just fine. But instead of adjusting its interval you calculate the distance your snake needs to move in the time that has passed since the last execution of your update timer function and set the position accordingly. e.g. set the interval to a fixed 20ms which gives you 50 position updates per second. Then you have your speed variable. This is the one you should be adjusting. And you execute as many position updates as required to match your set speed. Like newposition = oldposition + speed * time and time being your fixed 20ms interval . – Gerald Degeneve May 23 '14 at 22:51
  • Just to be a smart ass ... yes my answer did answer your question. "Why the Interval doesn't update for the intermediate values?" You even highlighted your question and used a bold font weight. – Gerald Degeneve May 23 '14 at 22:54