Module Border
  Andy's Blog
Module Border
Author: host Created: 3/6/2006 9:55 PM
Adventures in .NET

See you at MIX?
By Andy Beaulieu on 2/25/2008 10:11 AM

I'm very excited to be going to MIX next week! There will be a lot of great news surrounding Silverlight 2.0 Beta 1, and I'm looking forward to meeting some fellow Silverlight geeks in person.

I also got together with Bill Reiss and created a video for the Show Off Event on Thursday night, which centers around Silverlight and the Farseer Physics engine. Ok, we might end up on the cutting room floor, but it was a fun endeavor for sure.

Comments (2)

Silverlight 2.0 Teaser
By Andy Beaulieu on 2/22/2008 9:57 AM

Scott Guthrie gives a nice teaser today about the upcoming Silverlight 2.0 Beta. Lots of great stuff coming very soon!

(Update 2/28/2008) Scott has another teaser up, this time centering around using Blend as the designer for Silverlight.

Comments (0)

Advanced Physics with Silverlight and Farseer
By Andy Beaulieu on 1/22/2008 10:03 PM

UPDATE 10/14/2008: The source code download and demo have been updated for Silverlight 2 RTW.

In a previous post, I showed how we can quickly get started using Silverlight to create some great Physics games and simulations using the Farseer Physics Engine. In this post, I am going to show some more advanced physics effects using Farseer's Polygon Geometry.

We'll be creating kind of a "Sketch Pad on Steroids" where what the user draws becomes a physics object and "falls" to the ground. I can think of about a dozen game ideas you could implement with these techniques, including something like the jaw dropping Crayon Physics Deluxe.




Drawing a Path Using the Mouse

First let's look at how we can capture a series of x,y points that the user draws. If you look at Page.xaml.cs, you can see that when the user moves the mouse, we record all of their movements in a _polygonPoints, which is a Generic List of Point objects:

void Page_MouseMove(object sender, MouseEventArgs e)
    if (_drawActive)

        // draw the polygon

        if (_TempPolygonPath != null)



            _TempPolygonPath = null;



        _TempPolygonPath = Utils.CreatePathFromPoints(_polygonPoints, "tempPolygonPath");






We also call a function, Utils.CreatePathFromPoints, which creates a Path object based on the points, and add the Path to the page's Canvas: 

public static Path CreatePathFromPoints(List<Point> points, string name)


    Path path = new Path();

    path.Stroke = new SolidColorBrush(Colors.Magenta);

    path.StrokeThickness = 1;

    path.Fill = new SolidColorBrush(Colors.Transparent);

    PathGeometry pathGeom = new PathGeometry();

    PathFigureCollection figures = new PathFigureCollection();

    pathGeom.Figures = figures;

    PathFigure figure = new PathFigure();

    figure.StartPoint = new Point((double)points[0].X, (double)points[0].Y);

    figure.Segments = new PathSegmentCollection();



    foreach (Point point in points)


        LineSegment line = new LineSegment() { Point = new Point((double)point.X, (double)point.Y) };




    path.Data = pathGeom;


    return path;



...So that gives us a basic sketch pad, with all of the points stored in a buffer. But now we need to change that collection of points into a Physics object.


Creating our Polygon Physics


Remember to take a peek at my previous introductory post on using Farseer Physics with Silverlight, as I'll be skipping the basics. If you remember, we used a SpriteBase class to wrap the details of our physics objects. In this demo, I created a ucPolygon class which you can think of as a sprite - it just happens to be one that the user draws out.


Farseer differentiates between Bodies, which are the actual physics bodies that bounce and fly around, and Geometries, which are the shapes of the Body used for collision detection.


So we first need to define the shape of our physics geometry using a Vertices collection. Note that, in Farseer, coordinate points need to be based on 0,0 being at the geometry's center, so we will need to translate our drawn points on the Path/Canvas to the Geometry object. Take a peek at ucPolygon.xaml.cs, which creates the vertices collection:


// create the physics body
fsc.Vertices vertices = new fsc.Vertices();

foreach (Point point in points)
    // note vertices are based on 0,0 at center of body
x, y;
// first we need to remove the offset position of the drawn shape on the main canvas
x = (Convert
.ToDouble(point.X) - position.X);
    y = (Convert
.ToDouble(point.Y) - position.Y);

// we may need to offset position to get the point out of the negative
x = x + tweakX;
    y = y + tweakY;

// we need to make points relative to origin (center) of object
x = x - centerX;
    y = y - centerY;

    vertices.Add(new Vector2((float)x, (float)y));


We can then create our polygon's Body by calling CreateBody and passing in an instance of the Physics Simulator, the Mass of the object, and the moment of intertia. Note that there is a handy utility function on the Vertices class to calculate moment of inertia for us:

BodyObject = BodyFactory
.Instance.CreateBody(physicsSim, 0.5f, vertices.CalculateMomentOfInertia());


Finally, we create the actual Geometry object by calling CreatePolygonGeom and passing the simulator, body object,  vertices collection, and collsion grid cell size (you can tweak the collision grid if necessary for your application, but I found zero to be adequate for this demo).


fsc.Geom polygonGeometry = fsc.GeomFactory.Instance.CreatePolygonGeom(physicsSim, BodyObject, vertices, 0);


There is also a useful SetDebug method on the ucPolygon class, which will draw the center and boundary of the polygon. This was very useful during development as sometimes the Body and Geometry can get out of sync if you're not careful.


Conclusion and More Info

I am really impressed with how easily effects can be created using Silverlight's powerful UI and Farseer's friendly API. I can foresee some really great browser-based games in Silverlight's future!


A shout back to Cameron Albert who used and credited my SpriteBase Class and returned the favor with some helpful code on creating Path Geometries with Farseer! And to Jeff Weber and Michael Brooks who helped me with troubleshooting on the Farseer Forums.


One last note, debugging the collision behavior in Farseer can be quite frustrating until you get your arms around it. There is a good introductory document that can help you out with the specifics.

Comments (11)

Silverlight Talk at VDUNY
By Andy Beaulieu on 1/12/2008 4:21 PM

I will be giving a Silverlight talk on Wednesday, January 23rd 2008 at the Rochester, NY based Visual Developers of Upstate NY. The talk will cover Silverlight Basics and then move into some more advanced animation and input techniques. If you're in the area, come and check it out!


Comments (0)

Getting Started with Farseer Physics and Silverlight
By Andy Beaulieu on 12/21/2007 8:28 PM

I’m sure some of us may be taking a little break for the holidays, and might even get a few hours of coding time to sip from the firehose of technologies streaming out of Microsoft.


Might I recommend indulging in a little Silverlight game programming? J


To help you along, and as my gift for the holidays, I have put together an introduction to using Silverlight and Farseer Physics in perfect harmony.


Happy holidays!



The Farseer Physics Engine was created by Jeff Weber and later ported to Silverlight by Bill Reiss. Game programming with Silverlight is fun enough, but when you combine it with this easy to use physics engine, it’s almost as much fun to create games as play them!

In this walkthrough, I will be using the familiar “foobar” sprites from the Sort the Foobars game I posted last month.






The Ingredients

First, let’s cover what you will need for this walkthrough:


  1. Visual Studio 2008. I am using the Professional Edition, but you should be fine with Express as well.

  2. Microsoft Silverlight 1.1 Tools Alpha for Visual Studio 2008. This provides the silverlight templates for VS.

  3. Microsoft Silverlight 1.1 Alpha Refresh. This is the actual Silverlight plug-in, in case you have not already installed it.

  4. (Optional) Microsoft Expression Blend 2 December Preview. Recommended, but if you’re not into playing with the design stuff, you can skip this.

  5. (Optional) Farseer Physics Engine and Silverlight Samples.
    Recommended, because there are some really great Silverlight samples by Bill Reiss in the download.

Creating the Physics Simulator


The PhysicsSimulator class is your main communication channel with the Physics Engine. If we examine Page.xml.cs, we can see the create call, which passes in a value for gravity. In this case, gravity will be straight down in the vertical (y) direction with a value of 500:


PhysicsSimulator _physicsSimulator;

_physicsSimulator = new PhysicsSimulator(new Vector2(0, 500));

_physicsSimulator.Iterations = 10;


We also optionally set Iterations which will affect the precision of the physics calculations, at the cost of performance.


Creating the “Sprites”


User Controls are a convenient mechanism for creating and animating the characters (or Sprites) in your game. You can draw them out in Expression Blend, and even include Storyboard animations to bring them to life.


We need to be sure to add a RotateTransform and TranslateTransform to the User Controls. These will be required for integration with Farseer, since the physics engine will determine position and rotation of the sprites at all times.


In the demo application, there are three User Controls defined:


  1. ucHead.xaml – this is the cute little head that drops from the sky and slams into the ground. Note that there are two Storyboard animations defined for the head: timeLineMoveEyes, which gives the little bugger some life by moving his eyes around, and timeLineOuchy, which plays when the head collides with another sprite.

  2. ucGround.xaml – the grassy floor that the heads collide with initially.

  3. ucWall.xaml – this is used for both the left and right side “walls” which keep the little heads from bouncing off our playing field.


If we look at each the XAML for any of these user controls, we can see that there are two transforms defined for the main canvas:




      <!-- This transform conrols the rotation-->

      <RotateTransform x:Name="rotateSprite" Angle="0" CenterX="30" CenterY="30"/>

      <TranslateTransform x:Name="translateTransform" X="0" Y="0"/>




… these transforms will be used to keep the Farseer Physics Bodies in sync with our user controls’ positions. One thing to note which can be confusing is that the Farseer Engine keeps track of x,y position at the center of an object, instead of at the top left which we are used to. So the TranslateTransform will be used to keep that centered position of the object at our top, left position on screen.


Also note that each of these user controls inherits from SpriteBase instead of Control:


namespace HeadDrop


    public class ucHead : SpriteBase



This technique was explained in an earlier blog post, any allows for some OOP and code reuse. SpriteBase contains basic sprite information such as the Farseer Body Object, position, and state.


We also need to define the Physics Body and Geometry (for collisions) for each sprite. Let’s examine the code in ucHead.xaml.cs.


First,we define the Physics body, which gives the object a location and size in the simulated world. In the case of the “head sprites” we want to create a circular body to match their shape. We pass in an instance of the Physics Simulator, the radius of the circle, and a mass value:


BodyObject = BodyFactory.Instance.CreateCircleBody(physicsSim, (float)getWidth / 2, 0.5f);


Next, we define the Geometry of the sprite, which is used for collision detection by the Physics Engine. We call CreateCircleGeometry passing in the Physics Simulator, the BodyObject defined in the call above, the radius of the circle, and also a parameter called collisionGridCellSize – which is used to change the accuracy of collision detection at the cost of performance. Depending on your game or simulation, you may want to play with the value of collisionGridCellSize if you are seeing jittery movement or other collision issues.


fsc.Geometry headGeometry = fsc.GeometryFactory.Instance.CreateCircleGeometry(physicsSim, BodyObject, (float)getWidth / 2, 20);


Next, we set up the Collision event handler, which will fire when this sprite collides with other sprites in another CollisionGroup. We should also give the geometry a unique Tag value, as this is a handy way to identify it when collision events occur:


headGeometry.Tag = "headGood";

headGeometry.CollisionHandler += new FarseerGames.FarseerPhysics.Collisions.Geometry.CollisionHandlerDelegate(HandleCollision);



The Timer Event


Inside our Game Timer Event (_timer_Completed, implemented as a Storyboard), we need to be sure to update the Physics Simulator to a new point in time, so that it can calculate the new positions and velocities of all objects in the simulation. To do so, we simply call Update on the Physics object, passing in a time span that we wish to update to:




Once this call is made, the Body objects in the Farseer library will have the new positions calculated for all of our sprites (user controls). However, it is up to us to ensure that the sprites are actually moved to their new position in the UI. To ensure this, we call the Update method on all of our Sprites:


foreach (SpriteBase sprite in _spritesEnvironment)





foreach (ucHead sprite in _spritesHeadGood)





The implementation of this Update is contained in our SpriteBase class. This method synchronizes the X,Y position of the sprite to the X,Y position of the Farseer Body object:


public virtual void Update()


    if (BodyObject == null) return;

    if (_X != BodyObject.Position.X)


        _X = BodyObject.Position.X;

        RootCanvas.SetValue<double>(Canvas.LeftProperty, _X);


    if (_Y != BodyObject.Position.Y)


        _Y = BodyObject.Position.Y;

        RootCanvas.SetValue<double>(Canvas.TopProperty, _Y);


    if (BodyObject.Rotation != _rotation)


        _rotation = BodyObject.Rotation;

        RotationTransform.Angle = (_rotation * 360) / (2 * Math.PI);




Handling Collisions


If we look at ucHead.xaml.cs, we can see there is a HandleCollision event handler which we wired up above when creating the sprites:


private bool HandleCollision(fsc.Geometry g1, fsc.Geometry g2, fsc.ContactList contactList)



    if (BodyObject.LinearVelocity.X > 300 || BodyObject.LinearVelocity.Y > 300)


        // this was a fairly hard hit - begin the ouchy animation


        Random rand = new Random();



    // NOTE that we can track when two objects collide in the following way:

    // 1. add Tag values to each Geometry

    // 2. inside this event we compare tag values to see if a collision happened...

    if (g1.Tag.ToString() == "groundLeft" || g2.Tag.ToString() == "groundLeft")


        // collision happened               



    return true;



While this implementation of the Collision Handler is very simple, you can imagine that this would be a very handy method for triggering explosions and other events when two sprites collide.


In this example, we check if the LinearVelocity of the body is fairly high ( > 300) and if so, we play an “ouchy” animation which makes the little head frown because he has been hit L




I have only hit on the highlights of this sample, to help you understand how Silverlight and Farseer can work together. Hopefully the strategies I mentioned here will help you along in creating your own great physics games in Silverlight!

Comments (18)

Silverlight v2.0
By Andy Beaulieu on 11/29/2007 1:36 PM

Scott G. didn't keep us in suspense too long! He spilled the beans this morning about some of the new features coming for Silverlight - now dubbed v2.0.

With these improvements, it seems it will be viable to create full data-centric applications using Silverlight. And it looks like by first quarter 2008, a go live license will be available!

Goodbye, cruel AJAX/HTML/CSS/DOM/JavaScript world!!!


Comments (2)

VS 2008 RTM and Silverlight 1.1 Alpha
By Andy Beaulieu on 11/27/2007 7:36 AM

As Scott Guthrie notes, an updated version of the Silverlight 1.1 Tools Alpha is now available. If you are moving to the RTM release of Visual Studio 2008 and were previously using the Betas to do Silverlight 1.1 Alpha development, this is what you will need to to support the Silverlight project templates in RTM.

I think with this missing piece, I am finally ready to move my Silverlight development out of my virtual machine... although there is still at least one missing piece - Astoria - and according to this post, it looks like that won't be available until early December. 

But what really has me anxious is Scott's comment, "The next public preview of Silverlight will include a ton of new runtime features..." Come on Scott, don't be a tease!!! Please indulge us. :)

Comments (0)

Foobars and Farseer Phyiscs
By Andy Beaulieu on 11/9/2007 10:19 AM

My "coding for fun" time has been very scarce the past month because of some "coding for money" projects :) But I did have a little time to finally play with the Farseer Physics engine and create a "Sort the Foobars" game:

The object of the game is simply to get the ugly, zombie looking foobars into the left pen and the happy, healthy looking foobars into the right pen. Even though this is a very simple example, it shows how Storyboard animations (such as the Foobar's expressions) can be mixed with more complex animation supplied from the Farseer Physics engine.

If you haven't checked out Farseer yet, here are some great links to get started:

The Farseer Page on Codeplex

A Group of Demos by Bill Reiss (who ported Farseer to Silverlight)

A Nice Demo by the Farseer XNA Creator, Jeff Weber

Comments (4)

VS 2008 Beta 2 VPC and Silverlight
By Andy Beaulieu on 11/7/2007 3:53 PM

It's awesome that Virtual PC Images for Visual Studio 2008 Beta are made available. When I played with the Visual Studio 2005 Beta, I installed directly on my main development machine and it left some unwanted artifacts which later caused problems.

But here is something that has bit me a couple of times when using the VS2008 VPC's for Silverlight Development. If you happen to find that you can't bring up any Silverlight applications in the Internet Zone, keep in mind that there are some things disabled under Windows Server 2003 for security reasons that you must re-enable.

Here is what you need to tweak:

  1. Go to Tools/Internet Options
  2. Select the Security Tab
  3. Select Custom Level
  4. Under ActiveX Controls/Run ActiveX Controls and Plug-ins, Select Enable
  5. Under Script ActiveX Controls marked safe for Scripting, Select Enable.
Comments (0)

"Studio Enterprise Silverlight Toolset" from ComponentOne
By Andy Beaulieu on 11/5/2007 9:53 AM

Those of you like me that have been starving for Data Entry type controls for Silverlight 1.1 Alpha will be happy to know, there is yet another option!

ComponentOne has released an Alpha version of their "Studio Enterprise Silverlight Toolset" (codename Sapphire) which appears to have some very compelling data entry controls including basic stuff like buttons and containers and even advanced stuff like TreeViews and a DataGrid!!

This is the stuff that C1 demo'ed at REMIX07 last month (loved their lab coats and dry humor by the way).

Comments (1)

Module Border Module Border
Module Border
Module Border
RSS   Twitter
Module Border Module Border
Module Border
Module Border

This Windows app was created using Physics Helper XAML, and the Farseer Physics Engine.


This Windows Phone app was created using Silverlight, the  Physics Helper Library,  and the Farseer Physics Engine. It gets interesting when you import your friends photos and have your way with them!


This physics game won first place in the Server Quest Contest. Created using Silverlight , the Physics Helper Library,  and the Farseer Physics Engine.


A scrolling shooter game where the objective is to destroy the invading UFO's flying over a neighborhood of your choosing. Imagery provided by Microsoft Virtual Earth. Created using Silverlight.


These demos were created for the Physics Helper Library, which makes it easy to create physics games and simulations using Expression Blend, Silverlight, and the Farseer Physics Engine.


This little basketball game took first place in the TeamZoneSports Silverlight Contest. Created using Silverlight and the Farseer Physics engine.


A game where you need to sort the good foobars from the bad ones. Created using Silverlight and the Farseer Physics engine.


A demo showing polygon physics where the user draws physics objects with the mouse. Created using Silverlight and the Farseer Physics engine.


Destroy the asteroids before they destroy your ship! Created using Silverlight.


A simple game of harpoon-the-fish. Written using the AJAX Sprite Toolkit.


Module Border Module Border
Module Border
Module Border
Module Border Module Border
Module Border
Module Border
Module Border Module Border
Copyright (c) 2014 andy.beaulieu.com - Login