AquoS
Online Game Studio

Silverlight Game Design Tutorial

Tutorial Page 3 - Simple Animation
< previous page

In this tutorial I'll show you how to animate an image on the screen. Before proceeding further on this page, you need to at least know how to set up a game loop and how to display an image on the screen.

By the end of this tutorial you will have created a project that looks like this:

Get Microsoft Silverlight

Simple Animation

1. First of all, you need to find a picture that you want to display on the screen.
2. Click project -> Add existing item, then select the image you want. In this example, I selected the file "hello.png". You'll see this file added in the solution explorer.

3. Simply type these codes into your "Page.xaml.cs" file

using System.Windows.Media.Imaging;

namespace GameExample
{
    public partial class Page : UserControl
    {
        private Storyboard gameLoop;
        Image img1 = new Image();
        double fade = 0;

        public Page()
        {
            InitializeComponent();
            gameLoop = new Storyboard();
            gameLoop.Completed += new EventHandler(gameLoop_Completed);
            gameLoop.Duration = TimeSpan.FromMilliseconds(30);

            this.Resources.Add("gameloop", gameLoop);
            this.Loaded += new RoutedEventHandler(Page_Loaded);

            BitmapImage bmpImg = new BitmapImage();
            bmpImg.UriSource = new Uri("hello.png", UriKind.Relative);
            img1.Source = bmpImg;
            LayoutRoot.Children.Add(img1);
        }

        protected void Page_Loaded(object sender, RoutedEventArgs e)
        {
            gameLoop.Begin();
        }

        protected void gameLoop_Completed(object sender, EventArgs e)
        {
            fade = fade + 0.1d;
            img1.Opacity = 0.5 * (1 + Math.Sin(fade));
            img1.SetValue(Grid.WidthProperty, (1 + Math.Sin(fade))*200d);
            gameLoop.Begin();
        }
    }
}

4. Hit F5 to see the animated image.

Now lets see how this code works: Storyboard and Image are the same stuff from previous tutorials so I'll skip the explanation. We'll focus on the code inside the gameLoop_Completed method.

fade = fade + 0.1d simply increments the variable fade by 0.1 every frame.
We can make the image fade in and out by setting the value of img1.Opacity. Here we just use a Sin function to calculate the amount of opacity.
Next we stretch and shrink the image by setting the Grid.WidthProperty. Again we use a Sin function to calculate the size.
You may play around with the math to see how it affects the animation.

Tutorial Page 3 - Simple Animation
< previous page

Comments:


2011-07-14 05:45:57 Laquisha wrote:
Hey, that's the grteeast! So with ll this brain power AWHFY?


Post A Comment: