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>

 

源代码下载 

 

 原文链接

转载于:https://www.cnblogs.com/ueqtxu/archive/2008/12/10/timers-and-the-main-game-loop.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值