Part 4 – Three, two, one… launch!

Today we will setup the following scene:

It involves raising our floor a bit, introducing a pig into our world and handling user input in order to catapult it into our pile of boxes.

This will be a big post, so for the sake of sanity, it is split up in 3 parts:

  1. Raising the floor
  2. Introducing the pig
  3. Launching the pig
This will be the result afterwards:
Advertisements

Part 4c – Launching our pig

Part 4a & 4b were merely preparation for the big bang: catapulting our pig into the pile of boxes!

Our approach will be to wrap the pig Body in a Projectile object. The Projectile class will handle user input and launch controls.

To get information about user input, we need to call the the following method from within the Game.Update method:

TouchCollection touches = TouchPanel.GetState();

TouchPanel.GetState will return a collection of TouchLocation instances. Remember, every WP7 device is multi-touch capable, hence the collection.

TouchLocation has three properties:  a Position, a State and an Id.

The Position property is a Vector2 which holds the coordinates where the touch on screen happened. On a typical device it can range from (0,0) to (800,480).

The State property is an enum which can be either PressedMoved or Released.

The Id property can be used to identify the same touch as it goes from one state to another.
Remember that the Update method is called 30 times per second. Every time it is called you will get a new collection with the current registered touches. The Id of a touch will remain the same for the lifetime of the touch.

Imagine the following scenario:
Pressing your finger on the screen, then dragging it and releasing it again. This will result in a TouchLocation with a fixed Id and a State that goes from Pressed to Moved to Released. In a  multi-touch scenario the Id is invaluable to keep track of the different touches.

Our approach will be to capture a touch near the center of our pig, keeping track of that touch so we can draw the Pig being dragged until the touch is released which is translated into us launching the pig in the opposite direction of it being pulled.

The red cross is the center of our Pig body. Because we use our imprecise fingers as input device, we want to register any touch within a certain radius of this center. This is the yellow circle.
Finally, the green cross symbolizes the location of a touch we registered. It will almost always be off-center.
It is critical to keep track of the delta between the touch location and the pig’s center, since we will be animating the touch movement. If we were to draw the pig at the touch location, it would jump from its original position to the off-center location. By keeping track of the delta we can draw the pig at the corrected touch location. Hopefully the following image makes this clear:

Time to turn theory into code.

Below is the starting point for our Projectile class.


public class Projectile
{
	private const float TouchRadius = 0.5f;

	private Vector2 _touchOffsetFromCenter;
	private int _touchId;

	public Body Body { get; private set; }

	/// <summary>
	/// Shortcut to Body.Position
	/// </summary>
	public Vector2 Position
	{
		get { return Body.Position; }
	}

	/// <summary>
	/// User is dragging the projectile in order to launch it
	/// Where is the current drag position, taking offset correction into account.
	/// </summary>
	public Vector2 DragPosition { get; private set; }

	/// <summary>
	/// Is user dragging the projectile in order to launch it?
	/// </summary>
	public bool IsBeingDragged { get; private set; }

	public Projectile(Body body)
	{
		Body = body;
	}

	/// <summary>
	/// Handle user input
	/// </summary>
	/// <param name="gameTime">current gameTime</param>
	/// <param name="touches">TouchCollection</param>
	/// <returns>True if projectile handled input, otherwise false</returns>
	public bool HandleInput(GameTime gameTime, TouchCollection touches)
	{
	...
	}
}

First of all, we define how big the radius within we will accept a touch as a touch of our projectile (the yellow circle from before). 0,5f in simulation units equals to a circle with a radius 50 pixels around the center of our projectile.
Secondly ,we have two private fields, one to keep track of the off-center delta and another to keep track of the Id of the touch that hit our projectile.
Next, we define a couple of public properties we need to expose in order to have enough information in our Game.Draw method.
Finally, there’s the constructor that takes a Body as parameter. In our example this will be the pig body.

As said before, launching a pig is a three step process: touching the pig, pulling it back and releasing it.

We will implement HandleInput step-by-step:

foreach (TouchLocation touchLocation in touches)
{
	Vector2 touchPositionSim = touchLocation.Position / Constants.Scale;

	if (touchLocation.State == TouchLocationState.Pressed)
	{
		if ((Position - touchPositionSim).Length() < TouchRadius && !IsBeingDragged)
		{
			//start dragging the projectile, ready to shoot
			IsBeingDragged = true;
			//user never clicks dead-center on the projectile, this is the offset of the click compared to the center
			_touchOffsetFromCenter = Position - touchPositionSim;
			DragPosition = Position;
			_touchId = touchLocation.Id;
			return true;
		}
		break;
	}

	// handle Moved and Released
}

The above code should be fairly self-explanatory. If we find a touch within the touch radius and we’re not dragging an object yet, we start tracking the projectile and it’s off-center information.

Next, we implement the Moved status.
This should be very simple: set the DragPosition to the current touch location + the off-center vector.
There is a catch however! In our game we want to limit the distance our object can be dragged. There is actually a second, bigger radius around our pig’s center, beyond which it cannot be dragged.
We will add a field which holds this radius value.

private const float MaxDragRadius = 1.5f;

When we drag the pig around, we are actually creating a vector from the original Position to the current DragPosition.
This  vector has a length and if we notice its length is greater than the MaxDragRadius, we will normalize it and multiply it by this radius.
Normalizing the vector means that we keep the direction of the vector, but reduce its length to 1. Multiplying it by MaxDragRadius moves it to the outermost position it can be.

if (touchLocation.State == TouchLocationState.Moved && IsBeingDragged && touchLocation.Id == _touchId)
{
	Vector2 pullPosition = touchPositionSim + _touchOffsetFromCenter;
	Vector2 dragVector = Position - pullPosition;

	if (dragVector.Length() < MaxDragRadius)
	{
		DragPosition = pullPosition;
	}
	else
	{
		// if draggingbeyond max radius, limit to max radius.
		dragVector.Normalize();
		DragPosition = Position - Vector2.Multiply(dragVector, MaxDragRadius);
	}
	return true;
}
// handle Released

All that is left to do now is launching our projectile when the player lifts his finger.
We can do this by calling the ApplyLinearImpulse method on the Body. This method has two Vector2 parameters: impulse and point.
– we will use our dragVector as impulse, but we will multiply it by a factor that makes the impulse stronger in order to launch our pig far enough.
– the point parameter is a location relative to the origin of the World (not the object we’re applying the impulse to). We can use Body.WorldCenter to get the center point of our Body relative the World origin. To give our pig some backspin we will apply the impulse a bit lower than its center point (this is the CenterOffset you see in the code below).

private const float ImpulseModifier = 1.25f;
private static readonly Vector2 CenterOffset = new Vector2(0, 0.025f);
if (touchLocation.State == TouchLocationState.Released && IsBeingDragged && touchLocation.Id == _touchId)
{
	IsBeingDragged = false;
	Vector2 dragVector = (Body.Position - DragPosition) * ImpulseModifier;
	// apply an impulse to the Body, but a little bit off-center to give it a nice arcing motion
	Vector2 centerWithOffset = Body.WorldCenter + CenterOffset;
	Body.ApplyLinearImpulse(dragVector, centerWithOffset);
	return true;
}

All what’s left now is to wire up the projectile to our Game and Draw the dragged projectile.

Add the following to Game.Update:

TouchCollection touches = TouchPanel.GetState();
_projectile.HandleInput(gameTime, touches);

Add this to Game.Draw, right after the bodies and floor have been drawn:

if (_projectile.IsBeingDragged)
{
	PrefabUserData userData = ((PrefabUserData)_projectile.Body.UserData);

	spriteBatch.Draw(
		_sheet.Texture,
		_projectile.DragPosition * Constants.Scale,
		_sheet.SourceRectangle(userData.SpriteName),
		new Color(128, 128, 128, 128),
		_projectile.Body.Rotation,
		userData.Origin * Constants.Scale,
		1f,
		SpriteEffects.None,
		0f);
}

As a little side note: you will want to move the new Color(128, 128, 128, 128), which makes the projectile being drawn at half-transparency, to the Constants class in order to avoid the memory allocation on every frame.

Run the application at this point and this should be the result:

I’m giving out free tweets today, so you might want to follow me: http://www.twitter.com/jodegreef.

Part 4a – Raising the floor

Since we want to use a slingshot-like pullback motion to launch our pig, we need to make some space available on screen below the pig. We will raise our world’s ground floor up 60 pixels (= 1/8 of the vertical screen resolution)

We will change our old definition from

//Define the ground
float simulatedHeight = GraphicsDevice.Viewport.Height / Scale;
float simulatedWidth = GraphicsDevice.Viewport.Width / Scale;
BodyFactory.CreateEdge(_world, new Vector2(0.0f, simulatedHeight), new Vector2(simulatedWidth, simulatedHeight));

to

Constants.Initialize(GraphicsDevice);
//Define the ground
float simulatedHeight = Constants.FloorPosition.Y / Constants.Scale;
float simulatedWidth = (GraphicsDevice.Viewport.Width / Constants.Scale) * 2;
BodyFactory.CreateEdge(_world, new Vector2(0.0f, simulatedHeight), new Vector2(simulatedWidth, simulatedHeight));

The biggest notable change is the introduction of the Constants class, which we will use to store all our constants and magic numbers.

Constants.Pixels.FloorPosition is a Vector2 struct set to (0, 420), assuming our vertical resolution is 480 pixels high. We also widen our world’s width to twice the screen’s horizontal’s resolution.

Below is the source of the Constants class:

public static class Constants
{
	public const float Scale = 100f;
	public static float HalfScreenWidth { get; private set; }
	public static float ScreenWidth { get; private set; }
	public static Vector2 FloorPosition { get; private set; }

	public static void Initialize(GraphicsDevice graphics)
	{
		HalfScreenWidth = graphics.Viewport.Width / 2f;
		ScreenWidth = graphics.Viewport.Width;
		FloorPosition = new Vector2(0, graphics.Viewport.Height * 0.875f); // = 7/8
	}
}

To render our floor, I took this piece of existing artwork, added it the the Asset xml file and updated the Draw method.

spriteBatch.Begin();
// ...
// render bodies here ....
// ...
spriteBatch.Draw(
	_sheet.Texture,
	Constants.FloorPosition,
	_sheet.SourceRectangle("floor"),
	Color.White
	);
spriteBatch.End();

Continue to part 4B – hello piggy.

Part 4b – Hello piggy

With the floor raised, it’s time to add our pig.
The pig will be just another Prefab type.

Here’s a placeholder sprite with the right dimensions:

In the PrefabBodyFactory class, we add our pig as such, assuming the above image was saved as pig.png and ends up as such in our PigsFlySpriteSheet.xml file.

Library.Add(PrefabType.Pig, (world, position) => CreateRectangle(world, position, "pig", 0.5f, 0.59f));

Replace the old body creation code with the one below:

Body box1 = PrefabBodyFactory.CreateBody(PrefabType.GrayBox, _world, new Vector2(6.0f, 3.999274f));
_bodies.Add(box1);
Body box2 = PrefabBodyFactory.CreateBody(PrefabType.GrayBox, _world, new Vector2(6.0f, 3.612630f));
_bodies.Add(box2);
Body box3 = PrefabBodyFactory.CreateBody(PrefabType.GrayBox, _world, new Vector2(6.0f, 3.222778f));
_bodies.Add(box3);
Body pig = PrefabBodyFactory.CreateBody(PrefabType.Pig, _world, new Vector2(1.5f, 3.9f));
_bodies.Add(pig);
_projectile = new Projectile(pig);

To obtain these specific Y values, I let the bodies drop from a higher value and waited till they all fell and came at rest. Then it was only a matter of breaking the debugger and looking up these values of each body.

Run the code now and the result will be just like this:

Continue to part 4c – launching the pig.

Part 3b – supporting more prefab bodies

Last time we made our PrefabBodyFactory which allows us to easily create as many Body instances as we want.
However, we conveniently limited ourselves to 2 types of bodies which happened to be of the same size! We will rectify this in this post.

Remember that when we draw Bodies to screen, Farseer provides us with the position, based on the center point of the Body.
For a rectangle , the center point is

Vector2 origin = new Vector2(rectangle.width / 2f, rectangle.height / 2f);

In our current Draw method, we are taking advantage of the fact all of our Bodies have the same dimensions:

// pre-calculate the center point to use for all bodies, since we know they have the same dimensions.
Vector2 origin = new Vector2(_box.Width / 2f, _box.Height / 2f);

spriteBatch.Begin();

foreach (var body in _bodies)
{

	spriteBatch.Draw(
		_sheet.Texture,					// Texture
		body.Position * Scale,			// Position
		_sheet.SourceRectangle((string) body.UserData), // Source rectangle
		Color.White,					// Neutral
		body.Rotation,					// Rotation
		origin,							// Origin, relative to source rect size
		1f,								// Scale
		SpriteEffects.None,				// No effects
		0f);							// Z-layer
}

spriteBatch.End();

The code above breaks down once there is a item in _bodies which has different dimensions.

To solve this, we will store more information in the body.UserData:
– First of all we still need to store the sprite name
– Secondly, we want to store the center point

We will create a class to store these two properties:

public class PrefabUserData
{
	public string SpriteName { get; set; }
	public Vector2 Origin { get; set; }
}

Now we will adapt the PrefabBodyFactory to properly initialize the PrefabUserData:

private static Body CreateRectangle(World world, Vector2 position, string spriteName, float width, float height)
{
	Body body = BodyFactory.CreateRectangle(world, width, height, 1f, position);
	body.UserData = new PrefabUserData
			            {
			                Origin = new Vector2(width/2f, height/2f),
			                SpriteName = spriteName
			            };
	body.BodyType = BodyType.Dynamic;
	return body;
}

Similarly, we adapt our Draw method to make use of the PrefabUserData:

protected override void Draw(GameTime gameTime)
{
	GraphicsDevice.Clear(Color.CornflowerBlue);

	spriteBatch.Begin();

	foreach (var body in _bodies)
	{
		var prefabUserData = (PrefabUserData) body.UserData;

		spriteBatch.Draw(
			_sheet.Texture,					// Texture
			body.Position * Scale,			// Position
			_sheet.SourceRectangle(prefabUserData.SpriteName), // Source rectangle
			Color.White,					// Neutral
			body.Rotation,					// Rotation
			prefabUserData.Origin * Scale,	// Origin, relative to source rect size
			1f,								// Scale
			SpriteEffects.None,				// No effects
			0f);							// Z-layer
	}

	spriteBatch.End();

	base.Draw(gameTime);
}

From now on you can add more rectangular PrefabTypes and they will all render properly.

Finally, we will add support for circular-shaped bodies. Now that our Draw method has been made generic, we only need to change our PrefabBodyFactory.

Add the following method to the factory class:

/// <summary>
/// Create a body with a circular shape
/// </summary>
/// <param name="world">World</param>
/// <param name="position">Position in sim-units</param>
/// <param name="spriteName">Sprite name to render with</param>
/// <param name="radius">radius of the body in sim-units</param>
/// <returns>new instance of a Body</returns>
private static Body CreateCircle(World world, Vector2 position, string spriteName, float radius)
{
	Body body = BodyFactory.CreateCircle(world, radius, 1f, position);
	body.UserData = new PrefabUserData
	{
		Origin = new Vector2(radius),
		SpriteName = spriteName
	};
	body.AngularDamping = 2f; //without this, our ball would keep on rolling regardless of friction
	body.BodyType = BodyType.Dynamic;
	return body;
}

The code above should be self-explanatory by now.
The only line worth extra mention is the AngularDamping one. For non-circular bodies, the physics world does a great job of taking friction into account. For circles however, we need to specify this property on top of regular friction, otherwise they keep on rolling forever.
Omit the line and see the effect for yourself.

The final step to add circles to our world is to create a Circle PrefabType:

static PrefabBodyFactory()
{
	Library.Add(PrefabType.GoldBox, (world, position) => CreateRectangle(world, position, "box1", 0.4f, 0.4f));
	Library.Add(PrefabType.GrayBox, (world, position) => CreateRectangle(world, position, "box2", 0.4f, 0.4f));
	Library.Add(PrefabType.Ball, (world, position) => CreateCircle(world, position, "ball", 0.3f)); // new Ball type
}

Here’s the artwork that goes with the new Ball. It should be clear by now the circle should have a radius of 30 pixels and the sprite should be added to the spritesheet xml asset.

Add the new Ball to your world like so:

Body ball = PrefabBodyFactory.CreateBody(PrefabType.Ball, _world, new Vector2(3.8f, -0.75f));
_bodies.Add(ball);

This should be the result:


This concludes the creation of the PrefabBodyFactory. From this point on you can add more sprites and shape types. Take a look at the other methods offered by Farseer’s BodyFactory. You can create ellipses, rounded rectangles and so many more to make your levels interesting.

Next time we will take a look at catapulting an pig into a pile of boxes. This will involve taking user input (touch) and applying a force to our bacon cannon ball.

Tweets? http://www.twitter.com/jodegreef

Part 3a – A Factory to make Prefab bodies

Today we will improve the way we create Body instances in our physics world.

This is how we created them in Part 1:

//Create 2 boxes
Body box1 = BodyFactory.CreateRectangle(_world, 0.4f, 0.4f, 1f);
box1.Position = new Vector2(4, 0.75f);
box1.BodyType = BodyType.Dynamic;
box1.UserData = "box1"; // <-- the name of the texture as it was called originally
_bodies.Add(box1);
Body box2 = BodyFactory.CreateRectangle(_world, 0.4f, 0.4f, 1f);
box2.Position = new Vector2(4.2f, 0.0f);
box2.BodyType = BodyType.Dynamic;
box2.UserData = "box2"; // <-- the name of the texture as it was called originally
_bodies.Add(box2);

As you can see, a lot of code repetition and if we were to add more boxes, the repetition would only get worse.

To solve this issue, we will move the creation of new Body instances into its own specialized class: PrefabBodyFactory.

Indeed, if you look at a typical level in Angry Birds, you notice the same type of Body is reused several times:

Our PrefabBodyFactory will have only one public method.

/// <summary>
/// Create Body of certain prefab type
/// </summary>
/// <param name="type">prefab type</param>
/// <param name="world">Farseer world</param>
/// <param name="position">position of the body in the physics world (using simulation coordinates)</param>
/// <returns>a new instance of a Body</returns>
public static Body CreateBody(PrefabType type, World world, Vector2 position)

PrefabType is an enum, which will contain all our types of bodies.
In our example, we have two types of boxes so far: a golden one and a gray one. This means PrefabType looks like this:

public enum PrefabType
{
    GoldBox,
    GrayBox,
}

Time to take a look at PrefabBodyFactory.
The underlying idea is that we have a library of predefined shapes and each time we ask the factory to create a new instance of one of known types from the library.
This library is be implemented as Dictionary with as key our PrefabType enum and as value a delegate which takes the Farseer World and a position as input and returns a new Body.
In other words: our library is not a library of predefined shapes, but a library of methods creatings predefined shapes. This is important when we start to make a lot of instances of the same PrefabType: every instance should be a new instance.

/// <summary>
/// The PrefabBodyFactory will create new Body instances with specific, predefined settings
/// </summary>
public class PrefabBodyFactory
{
    private static readonly Dictionary<PrefabType, Func<World, Vector2, Body>> Library = new Dictionary<PrefabType, Func<World, Vector2, Body>>();
}
 /// <summary>
 /// Static constructor will initialize our library of prefab-shapes
 /// </summary>
 static PrefabBodyFactory()
 {
     Library.Add(PrefabType.GoldBox, (world, position) => CreateRectangle(world, position, "box1", 0.4f, 0.4f));
     Library.Add(PrefabType.GrayBox, (world, position) => CreateRectangle(world, position, "box2", 0.4f, 0.4f));
}
 /// <summary>
 /// Create Body of certain prefab type
 /// </summary>
 /// <param name="type">prefab type</param>
 /// <param name="world">Farseer world</param>
 /// <param name="position">position of the body in the physics world (using simulation units)</param>
 /// <returns>a new instance of a Body</returns>
 public static Body CreateBody(PrefabType type, World world, Vector2 position)
 {
     //will lookup the correct delegate in our prefab library and execute the delegate in order to create a new instance
     return Library[type](world, position);
 }

 /// <summary>
 /// Create a body with a rectangular shape
 /// </summary>
 /// <param name="world">World</param>
 /// <param name="position">Position in sim-units</param>
 /// <param name="spriteName">Sprite name to render with</param>
 /// <param name="width">width of the body in sim-units</param>
 /// <param name="height">height of the body in sim-units</param>
 /// <returns>new instance of a Body</returns>
 private static Body CreateRectangle(World world, Vector2 position, string spriteName, float width, float height)
 {
     Body body = BodyFactory.CreateRectangle(world, width, height, 1f, position);
     body.UserData = spriteName;
     body.BodyType = BodyType.Dynamic;
     return body;
 }
}

Given this new PrefabFactory we can now replace our original code with this:

//Create 2 boxes
Body box1 = PrefabBodyFactory.CreateBody(PrefabType.GoldBox, _world, new Vector2(4, 0.75f));
_bodies.Add(box1);
Body box2 = PrefabBodyFactory.CreateBody(PrefabType.GrayBox, _world, new Vector2(4.2f, 0.0f));
_bodies.Add(box2);

Give it a run and you’ll see the behaviour is still the same as before, but our code has become much cleaner.

In the next part we will finetune our PrefabFactory and Draw method in order to support more shapes types.

Part 2 – Sprite sheets

In Part 1 we saw how to create a physics simulation and how to render some objects to screen. Today we’ll go into more detail on rendering. Here’s a recap of our Draw method as it currently stands:

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null,null, null, transformationMatrix);
foreach (var body in _bodies)
{
	spriteBatch.Draw(_box, body.Position * Scale, null, Color.White, body.Rotation, origin, 1f, SpriteEffects.None, 0f);
}
spriteBatch.End();

The SpriteBatch object is a core XNA object that allows us to draw 2D textures on the screen. As its name implies it does so in batches. The nature of graphics cards is that they perform really well when given tasks in large batches.
Imagine a typical game screen: a multitude of different textures. SpriteBatch will have a hard time coping with this.

In order to speed up rendering we will combine all our textures (from now on referenced to as sprites) into one huge texture, called a sprite sheet.

Bing the term ‘spritesheet’ and you’ll find thousands of examples: www.bing.com/images/search?q=spritesheet&FORM=BIFD

Luckily we don’t have to create such a sprite sheet manually. On the App Hub site we can find a sample project which contains a content processor that does just this job.

What is a content processor? A content processor takes as input an asset (= a list of all our individual sprites) and performs some operations on it to transform the original asset into a more desirable asset (a sprite sheet containing all individual sprites combined).
It goes without saying this transformation happens at compile time, not at run-time, since we want run-time to be as fast as possible.

Let’s dive into code again:

Go to http://create.msdn.com/en-US/education/catalog/sample/sprite_sheet to download the sample code containing the sprite sheet content processor.

The sample code contains a solution where 2 projects are important for us:
SpriteSheetPipeline, containing the content processor.
SpriteSheetRuntime (Phone), containing a SpriteSheet class which is a wrapper to access our combined sprite sheet.

Add both projects to our own solution.

Add a reference from PigsFly to SpriteSheetRuntime. Add a reference from PigsFlyContent to SpriteSheetPipeline (Phone).

Upgrading our artwork from a simple red box, we now have 2 textures:

Texture for box1 Texture for box2

Save these images in the root of the PigsFlyContent project, but do not add them to the project. If you were to add them, they would become part of our game, which we don’t want. We only want the generated sprite sheet to be part of it.

Next add a new item to the PigsFlyContent project: Add | New Item -> XML File. Give it the name PigsFlySpriteSheet.xml

Add New Item - XML File

Edit the content of the new file to make it look like this:

<XnaContent>
	<Asset Type="System.String[]">
		<Item>box1.png</Item>
		<Item>box2.png</Item>
	</Asset>
</XnaContent>

Finally, take a look at the properties of the xml file and set the Content Processor to SpriteSheetProcessor:

Specify Content Processor

Given this preparation, we are now ready to use our brand new spritesheet.

We will revisit the LoadContent and Draw methods.

In LoadContent, load the sprite sheet as following:

SpriteSheet _sheet = Content.Load<SpriteSheet>("PigsFlySpriteSheet");

The SpriteSheet class has a Texture property, which returns the generated sprite sheet. We also have the following method at our disposal: Rectangle SourceRectangle(string spriteName).
Each sprite is defined by a Rectangle which contains the location on the sprite sheet where the sprite is located. Given the original sprite’sname, this method gives us that source rectangle. We will use this when rendering our bodies on screen.

Another change in LoadContent is that we will instruct each Body object which sprite it should use to render itself.

Farseer provides us with a UserData property on the Body class which can be used for any purpose we like. For now, we will store the original sprite name:

//Create 2 boxes
Body box1 = BodyFactory.CreateRectangle(_world, 0.4f, 0.4f, 1f);
box1.Position = new Vector2(4, 0.75f);
box1.BodyType = BodyType.Dynamic;
box1.UserData = "box1"; // <-- the name of the texture as it was called originally
_bodies.Add(box1);
Body box2 = BodyFactory.CreateRectangle(_world, 0.4f, 0.4f, 1f);
box2.Position = new Vector2(4.2f, 0.0f);
box2.BodyType = BodyType.Dynamic;
box2.UserData = "box2"; // <-- the name of the texture as it was called originally
_bodies.Add(box2);

We will now change our existing Draw method so it will render our two boxes with distinctive representations.
Because we use the same texture (= our sprite sheet) there will be no performance penalty for doing so.

spriteBatch.Begin();

foreach (var body in _bodies)
{
	spriteBatch.Draw(
			_sheet.Texture, // Spritesheet Texture
			body.Position * Scale, // Position
			_sheet.SourceRectangle((string) body.UserData), // Source rectangle, defines which subset of the spritesheet we will render
			Color.White,
			body.Rotation,
			origin,	// Origin, relative to source rectangle size
			1f, // Scale
			SpriteEffects.None,// No effects
			0f); // Z-layer
}

spriteBatch.End();

Here is the result:

Stalk me on twitter? Sure, why not? http://twitter.com/jodegreef