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.

      Loading XAML Dynamically

      Source code for this tutorial: http://silverlightrocks.com/cs/files/folders/slg101_tutorials/entry71.aspx

      By default, when you create a new Silverlight User Control, code is generated in the constructor which reads the associated XAML file and calls InitializeFromXaml to load it into the control. This is probably the most common option, but you can get some interesting results that would be difficult to do otherwise by changing this default behavior.

      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.

      Before we get started, there are a couple of methods in the Ship class that we will need in the Asteroid class, so let's move them to the Sprite class so that all of our sprites can access them. These methods are CreateVectorFromAngle and DegreesToRadians.

      Now create a new Silverlight User Control and call it Asteroid. Then go into the Asteroid class and change it to inherit from Sprite, like we did earlier for the Ship class, and add a using statement so that we can use Vector and any other utilities we may need:

      using SilverlightGames101.Utilities;
      

      By inheriting from Sprite, the asteroids will get all of the nice behaviors we added to the Sprite class, like position and velocity, and wrapping around the edges of the screen. The main thing we have left is to generate the XAML. Change the Asteroid.xaml to look like this:

      <Canvas xmlns="http://schemas.microsoft.com/client/2007" 
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
              Width="{1}"
              Height="{1}"
      >
        <Path x:Name="path" Data="{0}" Stroke="#FFFFFFFF" StrokeThickness="2" Width="{1}" Height="{1}"/>
      </Canvas>

      Notice the {0} and {1} placeholders. Anyone who has done some .Net programming probably has a good idea of what these are going to be for. In this case, we'll do a simple string replace using string.Format to create our dynamic XAML.

      I think it would be easiest at this point to list out the entire completed Asteroid class and step through some of the more important parts.

      namespace SpaceRocks
      {
          public class Asteroid : Sprite
          {
              FrameworkElement root;
              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)
              {
                  System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("SpaceRocks.Asteroid.xaml");
                  string pathXaml = "";
                  double[] lengths = { 1, 1, 1, .97, .97, .94, .94, .91, .91, .88, .85, .82, .82, .79, .76, .73, .61, .51 };
                  shuffle(lengths);
                  for (int i = 0; i < 18; i++)
                  {
                      float degrees = i * 20;
                      Vector v = CreateVectorFromAngle(degrees, radius * lengths[i]);
                      if (degrees == 0)
                      {
                          pathXaml += string.Format("M{0},{1} L", (int)v.X + radius, (int)v.Y + radius);
                      }
                      else
                      {
                          pathXaml += string.Format("{0},{1} ", (int)v.X + radius, (int)v.Y + radius);
                      }
                  }
                  pathXaml += "z";
      string xaml = string.Format(new System.IO.StreamReader(s).ReadToEnd(), pathXaml, radius * 2); root = this.InitializeFromXaml(xaml); Position = new Point(rand.Next(0, 640), rand.Next(0, 480)); Velocity = CreateVectorFromAngle(rand.Next(360), rand.Next(30, 70)); Width = radius * 2; Height = radius * 2; } } }

      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 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.

      So in the loop, for each of the shuffled lengths and a corresponding angle, we can generate a vector which represents the location of the point in X,Y space relative to the center of the asteroid.

      The first time through the loop, we need to do a "Move To" command (designated by "M") and in subsequent iterations, we need to do a "Line To" command (designated by "L"). In order to make the point relative to the center instead of the top left corner, we can add the radius to the vector value.

      Finally, to close the path, we add a "z" to the end.

      Next, let's create the xaml we will want to feed into InitializeFromXaml. To do this, we'll use a simple string.Format statement which replaces {0} with out dynamically generated path and {1} with double the radius, which is also the width and height of our asteroid.

      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<Asteroid> asteroids = new List<Asteroid>();

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

      for (int i = 0; i < 4; i++)
      {
          Asteroid a = new Asteroid(40);
          asteroids.Add(a);
          this.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 page. If you don't add your user control to the list of children for the page, they will not be displayed.

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

      for (int i=0; i<asteroids.Count; i++)
      {
          asteroids[i].Update(ElapsedTime);
      }

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

      asteroid_dynamic

      Posted: Jun 17 2007, 09:07 by Bill Reiss | Comments (12) RSS comment feed |
      • Currently 0/5 Stars.
      • 1
      • 2
      • 3
      • 4
      • 5
      Filed under:

      Comments

      Comments are closed