Wednesday, February 11, 2009

Silverlight Tip of the Day #4: Timers and the Main Game Loop

Main Game Loop

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
  • Animations - Updating objects and their positions.
  • Etc...

In this tip I will be demonstrating how to setup the main game loop using the DispatcherTimer. Alternate methods you should look into for your main game loop include:

  1. StoryboardTimer – 
  2. CompositionTarget.Rendering - 

My preferred method is using the CompositionTarget.Rendering event as the event is fired before the rendering of each frame.

Couple notes about DispatcherTimer:

  1. You will need to add a using statement: using System.Windows.Threading;
  2. If you set the timer interval to TimeSpan.Zero it will put the rate to be in sync with your monitors refresh rate.

Now, let’s take a look at the code. In the demo below we are simply displaying the number of frames per second our browser is rendering.

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:

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

Thank you, 

0 comments:

Post a Comment