How to control frame rate in WPF by using dispatcher timer accurately?

后端 未结 1 1896
时光取名叫无心
时光取名叫无心 2021-01-23 06:45

I have encountered a problem when I tried to control frame rate in WPF by using System.Windows.Threading.DispatcherTimer instance.

In order to try effectivity of Dispatc

1条回答
  •  遥遥无期
    2021-01-23 07:26

    Since WPF (and most other rendering engines) does not take an equal time amount to render every frame, and since different computations can further delay the interval between frames, you are right in using CompositionTarget.Rendering to "clock" the rendering intervals, but you can still use a "wall clock" timer to update your game at regular, rigorously controlled intervals.

    In the excellent book "Game Programming Patterns" (freely available online) you can find the very useful Game Loop Pattern.

    In its full form, this is what you would put inside a handler for the CompositionTarget.Rendering event (in pseudo-code):

      double current = getCurrentTime();
      double elapsed = current - previous;
      previous = current;
      lag += elapsed;
    
      processInput();
    
      while (lag >= MS_PER_UPDATE)
      {
        update();
        lag -= MS_PER_UPDATE;
      }
    
      render();
    

    In C#, you could implement getCurrentTime() either by calling DateTime.Now or by using Stopwatch.Elapsed, for example.

    0 讨论(0)
提交回复
热议问题