Wiki


Wiki Table of Contents

Page Details

Published by:
This page has not yet been rated

Silverlight Tip of the Day #16 - StoryBoard versus DispatcherTimer for Animation and Game Loops.

Trong  Tip of the Day #5  Tôi đã nói về cách làm sao để sử dụng  DispatcherTimer cho  main game loop( tạm dịch là vòng lặp game) của bạn. Tuy nhiên, còn có một phương pháp tiếp cận tốt hơn được sử dụng ở đây là  StoryBoard timer hay là sự kiện  CompositionTarget.Rendering  đã được thêm vào  Silverlight 2 trong thời gian gần đây. Hãy xem  Tip of the Day #50  để biết thêm nhiều về việc sử dụng sự kiện  CompositionTarget.Rendering cho  main game loop của bạn.

Theo sự nghiên cứu của tôi, nguyên nhân dẫn đến việc sử dụng StoryboardTimer tốt hơn là  DispatcherTimer vì những điều sau:

  1. StoryBoard được xử lý riêng trên một separate thread mà không chịu ảnh hưởng bởi UI thread , nhưng  DispatcherTimer chịu ảnh hưởng của  UI thread.
  2. DispatcherTimer giải quyết  timer  chậm hơn timer nằm phía sau lớp Storyboard, đây là nguyên nhân gây đến sự thất thoát trong  fidelity.
  3. Thực thi Storyboard trên các hệ điều hành và web browsers khác nhau tương đối ổn định.

Vì vậy, ta hãy xem thử cách mà nó được thực hiện. Trong ví dụ dưới đây, chúng ta tạo ra một StoryBoard timer và  increment (số lượng)  và hiển thị một biến đếm biểu thị cho số lần mà  MainGameLoop được gọi. Tôi đã đặt cho thời gian  giữa các lần gọi là  phần triệu giây nhưng bạn có thể thay đổi điều này bằng bất cứ gì tốt và thích hợp với  animation story của bạn.

Page.xaml.cs:

namespace SilverlightApplication8
{
    public partial class Page : UserControl
    {
        Storyboard _gameLoop = new Storyboard();
        int count = 0;
 
        public Page()
        {
            InitializeComponent();
            _gameLoop.Duration = TimeSpan.FromMilliseconds(0);
            _gameLoop.Completed += new EventHandler(MainGameLoop);
            _gameLoop.Begin();
        }
 
        void MainGameLoop(object sender, EventArgs e)
        {
            // Add any game logic/animation here.
            // Example:
            myTextbox.Text = count.ToString();
            count++;
 
            // Continue storyboard timer
            _gameLoop.Begin();
        }
    }
}

Page.xaml:

<UserControl x:Class="SilverlightApplication8.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="myTextbox">Display Counter</TextBlock>
    </Grid>
</UserControl>

Thank you,
--Mike Snow

 

Recent Comments

Leave the first comment for this page.