Wiki


Wiki Table of Contents

Tags

Page Details

First published by:
Last revision by:
This page has not yet been rated

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

Filed under: [Edit Tags]

Main Game Loop: (tạm dịch là Vòng lặp Game)

Main Game Loop như là trái tim(tâm điểm) của game. Trong chức năng này, bạn sẽ thực thi phần lớn các công việc có liên quan đến game như:

  • Game AI
  • Animations - Updating objects and their positions.(Cập nhật các đối tượng và vị trí của chúng)
  • Etc..

Trong bài này, tôi sẽ giải thích  làm cách nào để setup(tổ chức, bố trí)  main game loop sử dụng DispatcherTimer. Những phương pháp lần lượt được sử dụng trong game của bạn bao gồm:

  1. StoryboardTimer – Xem Tip of the Day #16
  2. CompositionTarget.Rendering -  Xem Tip of the Day #50.

Tôi thích cái phương pháp sử dụng sự kiện CompositionTarget.Rendering hơn tức là các sự kiện sẽ được vẽ trước khi  hiển thị mỗi frame.

Hai chú ý về DispatcherTimer:

  1. Bạn sẽ phải thêm vào một  using statement: using System.Windows.Threading;
  2. Nếu bạn gán timer interval cho TimeSpan.Zero nó sẽ làm cho tỉ lệ đồng bộ với tỉ lệ refresh  của bạn.

Nào, bây giờ hãy nhìn vào code bên dưới. Trong demo sau, chúng ta sẽ hiển thị 1 cách đơn giản số frame trên 1 giây (the number of frames per second)  trong browser của chúng ta được tiến hành:

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

Recent Comments

Leave the first comment for this page.