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

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)

By Andy Beaulieu on 10/9/2007 10:12 AM

Wow, even though I could only attend Day 1 of REMIX07, it was a very charging experience.

First, thanks to everyone who attended my "Silverlight for Casual Games" talk. You can download the slides and demos here:


It was an advanced talk, and I know I lost some people in the later examples, but I did get a lot of positive feedback!

It was kind of surreal having a "backstage pass" to the speaker's dinner on Sunday night. I literally rubbed elbows with Miguel de Icaza as we sat down to eat. And across the table from me were none other than Brad Abrams and Seema Ramchandani, PM on Avalon. Ugh, if only I could anticipate situations like this and have a bunch of intelligent questions ready! But I did learn from Miguel what kind of performance issues they are running into with Moonlight, and that it would be possible to port Moonlight to the Wii some day. And I also got great insight from Seema on just what drawing performance tricks Silverlight does (and does not do) under the covers. Seema posted a subsequent blog post with a great tip on seeing whether or not your code is causing redraws. I did not have my full "Silverlight Wish List" ready for Seema, but I did come up with a few items :)

I also had a chance to meet Bill Reiss, of Dr. Popper and Farseer Physics fame, and had some great conversations with him centering around using his physics engine with Silverlight Path objects, performance, and other great stuff.

And I had great conversations with Chip Lemmon, who is a Virtual Earth guru, centering around Birds-eye imagery and other VE technology.

Comments (1)

Code Camp 8 Slides and Demos
By Andy Beaulieu on 9/30/2007 7:17 PM

Thanks to everyone who attended my "Advanced Animation and Input with Silverlight" presentation at Code Camp 8! I actually had a good turnout for my talk, despite being scheduled against the noted Richard Hale Shaw (ha, thanks Chris!)

You can download the slides and demos here.

Comments (1)

Upcoming Events
By Andy Beaulieu on 9/5/2007 10:11 AM

I'll be doing a few Silverlight talks in the coming weeks at these events in the Northeast. REMIX looks especially cool so if you're in the area come and check 'em out!

CNY .NET Developer Group
9/5 (TONIGHT!) at 6:00pm "Playing with Silverlight 1.1"

Code Camp 8: Rise of the Silverlight Surfer
9/29 - 9/30 "Silverlight: Advanced Animation and Input Techniques"

10/8 - 10/9 "Silverlight for Casual Games"
UPDATE: You can use the following RSVP code, RM07EXTB, to save $100 off the registration fee!

Comments (0)

Silverlight for Linux
By Andy Beaulieu on 9/5/2007 8:20 AM

I was excited today when I learned from Scott's post about a Microsoft/Novell partnership to provide support for Silverlight on Linux.

Not because I want to run my Silverlight apps under Linux, nor do I expect there to be a huge user base of Linux users accessing my Silverlight apps. Although all that is very cool.

I am excited because I think this acknowledgement of Moonlight will be the beginning of "Silverlight Everywhere." Since the Moonlight source code will be available for coders to port to other platforms, look for Silverlight coming soon to your Wii or iPhone!

You have to wonder how long before Microsoft makes Silverlight Open Source as well... It seems to only make sense since the competition did so earlier this year.

Comments (0)

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