• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
ueqt
博客园    首页    新随笔    联系   管理    订阅  订阅

Silverlight Tips of the Day 系列翻译与领悟#5

 

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

游戏主循环

游戏主循环是游戏的核心. 在这里你将执行游戏的主要任务,包括:

  • 游戏AI 
  • 动画 - 更新物体以及它们的位置。
  • 等等...

在这章里我将演示如何使用DispatcherTimer建立游戏主循环。在游戏主循环中可选的方法包括:

  1. StoryboardTimer – 参看 Tips of the Day #16
  2. CompositionTarget.Rendering -  参看 Tips of the Day #50.

我推荐使用的方法是在渲染每一帧之前监听CompositionTarget.Rendering 事件:

  1. 你需要添加using: using System.Windows.Threading;
  2. 如果你把定时器的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>

 

源代码下载 

 

 原文链接

posted @ 2008-12-10 14:04  ueqt  阅读(178)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3