Silverlight Games 101

Write games in Silverlight 2 using C# by Bill Reiss
Our upcoming Silverlight book for beginners (includes a great chapter on game development in Silverlight!) Hello! Silverlight 2 with Dave Campbell, available online now!



Pages

    Recent posts

    Navigation

    Archive

    Blogroll

      Tampa Divorce Lawyer

      North of Tampa in Lutz, Florida. A Tampa Divorce Lawyer focusing on family, divorce, and real estate law.

      Disclaimer

      The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

      Generating Asteroids for the Game

      Source code for this tutorial: http://www.bluerosegames.com/silverlight-games-101/samples/GeneratingAsteroids.zip

      In the original asteroids arcade game, the asteroids themselves were randomly assigned from a predefined set of shapes. I thought it would be more interesting to dynamically generate the outline of each asteroid as we create them.

      The first this we want to do is move the CreateVectorFromAngle and DegreesToRadians methods to another class and make them static and public so that we can use them other places. So in the BlueRoseGames.Helpers project there is a new class called MathHelpers and this is the MathHelpers.cs file:

      using System;
       
      namespace BlueRoseGames.Helpers
      {
          public static class MathHelpers
          {
              public static double DegreesToRadians(double degrees)
              {
                  double radians = ((degrees / 360) * 2 * Math.PI);
                  return radians;
              }
       
              public static Vector CreateVectorFromAngle(double angleInDegrees, double length)
              {
                  double x = Math.Sin(DegreesToRadians(180 - angleInDegrees)) * length;
                  double y = Math.Cos(DegreesToRadians(180 - angleInDegrees)) * length;
                  return new Vector(x, y);
              }
          }
      }

      Change the existing Sprite code to call these static methods instead.

      Now create a new Silverlight User Control in the SpaceRocks project and call it Asteroid.xaml. Add a using statement so that we can use Vector and MathHelpers:

      using BlueRoseGames.Helpers;

      What we’ll do for our asteroids is take a few angles around the circle and using some randomly shuffled radius values, generate a polygon. Then we’ll make these asteroids the content of Sprite objects to get things like positioning, velocity, and wrapping.

      First, change the Asteroid.xaml to have a Canvas for the LayoutRoot and remove the Background property:

      <UserControl x:Class="SpaceRocks.Asteroid"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
          Width="400" Height="300">
          <Canvas x:Name="LayoutRoot">
       
          </Canvas>
      </UserControl>

      The Height and Width don’t matter since we’ll explicitly set those in the constructor anyway. It’s important that we set the Width and Height so that the Sprite object that wraps the Asteroid knows how big to make itself.

      Here is the code behind for the asteroid:

      using System;
      using System.Windows;
      using System.Windows.Controls;
      using System.Windows.Media;
      using System.Windows.Shapes;
      using BlueRoseGames.Helpers;
       
      namespace SpaceRocks
      {
          public partial class Asteroid : UserControl
          {
              static Random rand = new Random();
       
              void shuffle(double[] lengths)
              {
                  for (int i = 0; i < 100; i++)
                  {
                      int i1 = rand.Next(lengths.Length);
                      int i2 = rand.Next(lengths.Length);
                      if (i1 != i2)
                      {
                          double tmp = lengths[i1];
                          lengths[i1] = lengths[i2];
                          lengths[i2] = tmp;
                      }
                  }
              }
       
              public Asteroid(int radius)
              {
                  InitializeComponent();
                  this.Width = radius * 2;
                  this.Height = radius * 2;
                  double[] lengths = { 1, 1, 1, .97, .97, .94, .94, .91, .91, .88, .85, .82, .82, .79, .76, .73, .61, .51 };
                  shuffle(lengths);
                  Polygon poly = new Polygon();
                  poly.Stroke = new SolidColorBrush(Colors.White);
                  poly.StrokeThickness = 1.5;
                  for (int i = 0; i < 18; i++)
                  {
                      float degrees = i * 20;
                      Vector v = MathHelpers.CreateVectorFromAngle(degrees, radius * lengths[i]);
                      poly.Points.Add(new Point(v.X + radius, v.Y + radius));
                  }
                  LayoutRoot.Children.Add(poly);
              }
          }
      }

      The shuffle() method will take an array and shuffle the elements of the array randomly, like in a deck of cards. In our case, we will be shuffling distances from the center of the object.

      Notice that I have added a radius parameter to the Asteroid constructor. This will allow us to easily create asteroids of varying sizes.

      The first thing to do is set the height and width of the asteroid based on the radius, then the lengths array is a series of percentages stored as double values. The lengths array determines for each of 18 points along the outside of the asteroid (one for every 20 degrees) how far that point will be from the center, with a value of 1 representing a distance equal to the radius, and a value of .5 would be half of the radius.

      This array is shuffled so that the percentage values are mixed up and each asteroid will look differently. I use this technique instead of just randomly generating the distance from the center values to avoid asteroids with values that fluctuate too much or ones where you get a bunch of small values, etc. This seems to work pretty well.

      Next we create our polygon, and going in 20 degree intervals, calculate the vector from the center for each point and add the point to the points collection for the polygon. Then we add the polygon to the root canvas for the Asteroid control.

      Then all that's left is to randomly generate a starting position and velocity, and to set the Width and Height properties of the user control (inherited from Sprite).

      Ok so now to use this class. In the Page class, add a field to hold a list of Asteroids:

      List<Sprite> asteroids = new List<Sprite>();

      and then, at the end of the Page_Loaded method, add the following:

      for (int i = 0; i < 4; i++)
      {
          Sprite a = new Sprite(new Asteroid(40));
          asteroids.Add(a);
          gameSurface.Children.Add(a);
      }

      Note that the asteroids are added both to our list of Asteroids (so that they can be easily accessed later in the Update and other methods) and to the list of Children for the game surface. If you don't add your user control to the list of children for the game surface, they will not be displayed.

      Then to move the asteroids, in the gameLoop_Update method, add the following:

      foreach (Sprite asteroid in asteroids)
      {
          asteroid.Update(elapsed);
      }

      so if all went well, if you run the program, you should see 4 asteroids floating around.

      asteroids

      Posted: Nov 23 2008, 22:25 by Bill Reiss | Comments (32) RSS comment feed |
      • Currently 0/5 Stars.
      • 1
      • 2
      • 3
      • 4
      • 5
      Filed under:

      Comments

      Comments are closed