Mike Snows Silverlight Blog

Game Programming with Silverlight 2.0

Tip of the Day #5: Timers and the Main Game Loop

Main Game Loop

***NOTE: Please see Tip of the Day #16 – I have found that using the StoryBoard control is a better choice for your MainGameLoop. I am keeping this blog only to illustrate how to use the DispatcherTimer.

The main game loop is the heart of your game. In this function you will execute the majority of your game related tasks including:

  • Game AI
  • Updating objects and their positions.
  • Drawing of a single frame.
  • Etc...

Couple notes:

  1. Adding a using statement for the DispatcherTimer: using System.Windows.Threading;
  2. Set the timer interval to TimeSpan.Zero. This will put the rate to be in sync with your monitors refresh rate.

Page.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
 
namespace SilverlightApplication6
{
    public partial class Page : UserControl
    {
        private DispatcherTimer _gameLoopTimer;
        private int _fps = 0; 
        private DateTime _lastFPS = DateTime.Now;
 
        public Page()
        {
            _gameLoopTimer = new DispatcherTimer();
            _gameLoopTimer.Interval = TimeSpan.Zero;
            _gameLoopTimer.Tick += new EventHandler(MainGameLoop); 
            _gameLoopTimer.Start();
 
            InitializeComponent();
        }
        void MainGameLoop(object sender, EventArgs e)
        {
            _fps++; 
            if ((DateTime.Now - _lastFPS).Seconds >= 1) 
            { 
                FPS.Text = _fps.ToString() + " FPS"; 
                _fps = 0; 
                _lastFPS = DateTime.Now; 
            }
        }
    }
}

Page.xaml:

<UserControl x:Class="SilverlightApplication6.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="FPS">Current FPS</TextBlock>
    </Grid>
</UserControl>

Thank you,
--Mike Snow

 Subscribe in a reader

Comments

Dew Drop - April 2, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - April 2, 2008 | Alvin Ashcraft's Morning Dew

# April 2, 2008 9:45 AM

14 Silverlight Tips | DavideZordan.net said:

Pingback from  14 Silverlight Tips | DavideZordan.net

# July 2, 2008 4:30 AM