Silverlight Tip of the Day #5: Timers and the Main Game Loop
游戏主循环
游戏主循环是游戏的核心. 在这里你将执行游戏的主要任务,包括:
- 游戏AI
- 动画 - 更新物体以及它们的位置。
- 等等...
在这章里我将演示如何使用DispatcherTimer建立游戏主循环。在游戏主循环中可选的方法包括:
- StoryboardTimer – 参看 Tips of the Day #16
- CompositionTarget.Rendering - 参看 Tips of the Day #50.
我推荐使用的方法是在渲染每一帧之前监听CompositionTarget.Rendering 事件:
- 你需要添加using: using System.Windows.Threading;
- 如果你把定时器的interval设置为TimeSpan.Zero,它将把速度保持与你的显示器刷新速度同步。
现在,让我们来看代码吧。在下面的演示中我们简单地输出FPS(每秒运行了多少帧)。
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>