About me

Hi I’m Roy Triesscheijn. Born 1988, Leiderdorp, the Netherlands. I currently live in Utrecht where I study Game & Media technology at Utrecht University. When I'm not studying I work as a freelance expert in science exhibits, serious games and event management. A remnant of my past work at Science LinX. Of course I don't only work and learn. I play a fair game of basketball, enjoy listening to all sorts of music (be it pop, rock, progressive, ambient, electronic, jazz, anything goes), watching movies and of course writing software. Recently I've started an internship at Abbey Games.

Got any questions? Feel free to use the comments, send me a tweet or e-mail me.

In the last two tutorials I’ve told you how to set up Farseer with XNA and how bodies and joints work. We’re going to use the techniques from these tutorials to create a character for a platformer game, think Mario or Kirby or whatever your favorite platformer character is! It’s not too obvious how to create a character in Farseer. Just applying forces to a rectangular body works OK, but traveling slopes becomes really tricky in this case and the ability to stop moving instantly becomes even more hacky (usually done by pinning the character to the background with a joint). Because of that I will use a technique described by Bryan Dismas and Robert Dodd where we create a character by combining a motorized wheel and a rectangular with an axis joint and fixed angle joint (see the previous tutorial) to create a character.

Platformer character composition

So let’s start off. First things first. I made some small changes to the DrawablePhysicsObjects class to allow circular bodies. I also found a bug in the drawing (which only happens with circular bodies). So let’s add the following constructor to the DrawablePhysicsObjects class:

As you can see the player is a composition of two DrawablePhysicsObjects: a torso and a wheel as mentioned above. The constructor is fairly standard, we need a texture for the torso and wheel. We need a size for the player, a mass and a start position. Let’s start implementing these details!

First, because the player is a composition, we need to calculate the sizes of the wheel and torso. We want the wheel to be just as wide as the player and to form the lower part of the body (note that this technique won’t work for characters that are wider than they are high!)

Let’s also implement a draw function, which is extremely simple because we can use the drawing facilities of the two DrawablePhysicsObjects. Note that in a real game you would just draw one animated sprite over the entire player but for this tutorial this will suffice.

Ok. Run your game. If everything went well you will see your player character fall from the sky, land, and be pushed away by one of the paddles we added in the previous tutorial. You can see a body and a wheel and that they are connected. You will notice that the character keeps sliding a lot before it stands still when it’s pushed by the paddle. Based on your game this might be desirable or undesirable. You can control this behavior using the friction of the wheel. I don’t want the character to slide so much so I’ve added a bit of friction to the wheel by adding the following line in the constructor of player.

wheel.Body.Friction = 0.8f;

Higher values will stop the character from sliding at all.

Now to make the scene more interesting we will have to be able to control the player. Let’s first add movement and then later add jumping as well. Create the following enum:

Then go to the update function of your game class and add the following lines:

Run the game again. You should now be able to control your character. Remember that you can still press space to make some boxes fall from the sky, push them around a bit. Depending on how high you’ve set the friction of your wheel body and (max) torque of your revolute joint you might be able to push none, one or quite a few more!

Now the finishing touch is obviously jumping, and with just adding a bit of force we can get there. Add the following fields and method to the Player class:

As you can see we do some management to keep track of when we last jumped. The jumping itself is done by adding impulse to the torso body and since the wheel is connected to the torso body we don’t need to do anything else. Simple right? Let’s hook this jump function up to the left control key by adding these last few lines to the Update function of your game class.

In the previous tutorial, which you can find here, we created static and dynamic bodies. In this second tutorial we are going to take a look at joints. Simply said a joint is used to make a connection between two bodies or a body and the background. The place where a joint is attached is called the anchor. Usually a joint has two anchors. One placed on the first body and one placed on a second body or on the world itself. Farseer uses the following naming convention for this. If a joint is ‘fixed’ it provides a joint between a body and the background/world. If a joint is not fixed it is used to connect two separate bodies to each other. So a RevoluteJoint connects two bodies and a FixedRevoluteJoint connects a body and the background/world.

Overview of joints

There are quite a few types of joints in Farseer:

Standard joints

Angle joints

Keeps a body at a fixed angle from another body or the world.

Distance joints

Keeps a body at a fixed distance from another body or from an anchor in the world.

Friction joints

Applies translational and angular friction to a body.

Line joints

A line joint can best be seen as a spring. It linearly connects to bodies (or a body and the background) together and tries to keep them at a fixed distance. It does not limit relative rotations but it does limit translation over one axis. They can be a bit tricky to place since the mass of the bodies themselves already affects the distance between the two bodies so setting the ‘at rest’ state is a bit of trial and error. Note that Line Joints are a new addition to Farseer and are not available in Box2D.

Prismatic joints

Revolute joints

The most standard joints. Allows a body to rotate around an implicit axis coming from the screen (Z-Axis). Can be used to connect a body to the background or to another body. Can be motorized.

Slider joints

A sort of prismatic joint that doesn’t limit the bodies to just linear motion. Best described as a combination of a revolute joint and a prismatic joint. Note that Slider Joints are also not available in Box2D.

Weld joints

Connects two bodies together disallowing any form of relative rotation/translation.

More complex joints

Gear joints

Connects two revolute joints or a revolute joint and a prismatic joint. Simulates that they are connected by gears so if the body on the first revolute joint rotates the body on the second revolute joint will rotate in the opposite direction.

Pulley joints

Used to create a pulley system. (Two bodies both connected to a rope that runs over a pulley). Can be used to create sophisticated elevators.

If you would like to know more about the joints Farseer offers you can check the Box2D documentation here (Farseer is a C# implementation of Box2D, and although it’s growing slowly to become more than that the best place for documentation is still the Box2D website).

Refactoring last week’s example

After doing some coding I found that I need access to the world-to-screen and screen-to-world conversion methods for the joints and they are currently members of the DrawablePhysicsObject class. So before we start creating or own joints we must first refactor last week’s example.

And then update the DrawablePhysicsObject class to use the helper class.

Some setup

Last week we added a list to store all the boxes that we randomly spawn. This week we’re going to create ‘paddles’ connected by joints. To store the paddles we’re going to need another list. So open Game1.cs and add the following field:

I’ve also added another image to the content project called ‘Paddle.png’.

Adding some bodies and joints

Now to demonstrate how to use joints I’m going to create three paddles. The first paddle will just be a simple body connected with revolute joint to the background. This means that it can spin freely. The second paddle is almost the same, but it will be motorized, adding some interaction to the scene. Finally we combine two line joints to create a trampoline. After this you should have a basic understanding on how joints work in Farseer.

A simple revolute joint

Add the end of the LoadContent method initialize the list we use to store the paddles. Then after that add the following code to create the first paddle:

As you can see we first create a simple body, just as in the previous tutorial. The body is 128 pixels wide and 16 pixels high (note that the constructor of the DrawablePhysicsObject converts these units to world coordinates). It has a mass of 10KG. Note that we don’t have to set the position of the body. This is implicitly done by the joint, which fixes the body on the background at the anchor positions.

Next we create the joint. The first argument is our physics simulation and is used to register our joint to the simulation. We then pass the body this joint should be applied to. Since this is a Fixed joint we don’t need to pass a second body. The joint will connect the first body to the world. We then have to give some coordinates. We pass the center of the body (0,0) and somewhere in our world. Note that we use the conversion methods to go from pixel to world coordinates. Also don’t forget the last line, where we add the paddle to our list of paddles, else it won’t show up for drawing.

You can now run the simulation. Again press space to drop crate, you will see that we’ve create a small paddle that rotates freely when hit by a crate.

Again we create a body and a Fixed Revolute Joint. But this time we store the joint created by the joint factory in the variable j so that we can access the properties of the joint. The revolute joint exposes a few interesting properties. The most interesting one is to motorize it. We’ve set a motor speed of pi/2. This means that the every second the joint will rotate the connected body by pi/2 radians, or a 1/4 of a circle. We also have to set the torque to give the motor enough power to rotate the body and to keep rotating even when a few crates are blocking the paddle. We also set the max motor torque and enable the motor. Again in the last line we add the paddle to our list of paddles so that it will be drawn.

A trampoline

To create a trampoline we will use two Line Joints (a sort of springs) to connect a paddle to the ground. This way we create some sort of trampoline. Add the following code:

Now the creation of the body should look really familiar now. Note that this time we do have to set the position of the body. The line joint will try to keep the paddle and the ground at roughly the same position as the starting position from each other so it needs some initial position.

We create two joints, they are exactly the same, except for where they connect to the paddle. One is anchored on the left side of the paddle and one on the right side. So I will only explain the first line joint.

We start by passing the body of the first body the line joint should connect to, the floor. We then pass the body of the paddle. We tell the line joint to connect to the paddle at the given relative coordinates. We then give the axis of freedom the line joint should offer. In our case the Y-Axis.

We also set some properties, CollideConnected means that the paddle and the floor can collide with each other. Handy now but for a wheel inside a car you might want to keep this at the default, turned off, state. We also set a nice frequency and damping ratio. Finally we add the joints to the world. Don’t forget this step! Only Fixed joints are automatically added to the world. We also add the paddle to our list of paddles to draw.

You can now run the simulation again. Try to drop a few crates on the trampoline, you will see that it behaves quite nicely.

Conclusion

Joints in Farseer are fairly easy to use and can add a dynamicity lot to your scene. Try playing around with all different joints to get a feel from them. All joints in Farseer are created using a way similar as shown in this tutorial. In the next tutorial we will add a controllable character and create a small platformer.

A physics engine, like Farseer, is a piece of technology that allows you to simulate real-world-physics inside your game. It enables you to incorporate elements like gravity, weight, collision detection/response and much more into your game without having to rediscover and implement the laws of physics yourself.

Farseer is one of the most used physics engine for 2D games in C# and XNA, it’s tries to mimic the functionality of the popular Box2D physics engine which was built with C++ in mind. Note that you can also use Farseer if you’re not using XNA, it also has bindings for Silverlight and plain C#/.Net.

A while ago I wrote a tutorial for Farseer 2.X on how to create and manipulate a character and how to setup a few platforms and a seesaw. That tutorial still remains popular but since then a lot of things have changed in the newer versions of Farseer so I think it is useful to revisit this topic.
This tutorial is the first in a series. The end result will be the same as the old platformer tutorial but we’ll get there in byte sized pieces this time and I’ll try to go a bit more in depth. Anyway, let’s get started!

Setting up Farseer and XNA

Ok so first things first, start visual studio and create a new XNA 4 Windows Game Project. You can then download the Farseer Physics Engine from here. At the time of writing the latest version was v3.3.1. Extract the archive and open the Visual Studio solution named ‘Samples XNA’. Switch to Release mode and build the project named ‘Farseer Physics XNA’. Now in the output directory (bin/x86/release) find the file ‘FarseerPhysicsXNA.dll’ and copy it to your game project. Switch back to the your own game project (you can close the other Visual Studio window). Locate the references in the solution explorer, right click it and click ‘Add Reference…’ browse to your project folder and select ‘FarseerPhysicsXNA.dll’. You can now use Farseer in your XNA project!

Setting up a simple physics simulation

Now let’s get some physics going. Open Game1.cs and add the following using statements at the top of the file.

using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;

Also add the following member to the Game1 class.

World world;

The World class is the most important class in Farseer. It represents the entire physics simulation. Every object that influences the simulation should be registered with your instance of the world class. Of course to make it work we have to instantiate it and tell it what kind of gravity we want. To do so add the following to your LoadContent() method.

world = new World(new Vector2(0, 9.8f));

As you can see I’ve chosen a gravity of 0m*s^2 on the horizontal axis and 9.8m*s^2 on the vertical axis. Just as on earth!
The world object needs to do some work every frame to keep the simulation going so add this to your update method:

world.Step((float)gameTime.ElapsedGameTime.TotalSeconds);

Now we still wont see anything, there aren’t any objects, or bodies as they are called in Farseer, yet in our simulation. Lets remedy this situation by adding a crate. Add the following member to Game1.cs

Now as you can see we use a handy factory to create a rectangular body, we pass the world object so that it can be registered to it. However when passing the size of the body we first multiply this by the newly introduced constant pixelToUnit. Farseer uses Meters, Kilograms and Seconds as units while we are using pixels. So we need to convert all sizes and lengths to meters when we pass them to Farseer by multiplying them with pixelToUnit and, vice versa, when we get data back from Farseer, for example the position of a body, we need to convert back from meters to pixels. We use the same idea when setting the body’s position.

We also set the body type to Dynamic. This is a normal body, you also have Static, which means that it is immovable and Kinematic which means that it has no mass and some other properties (we wont use it).

Anyway add an image for the crate to your content project, I’ve named mine ‘Crate.png’. Then add the following member to Game1.cs.

Texture2D texture;

Now we can finally draw something to the screen. Add the following code to your Draw method

When you run the game now you should briefly see a crate fall to its doom before it disappears from the screen.

A more interesting simulation

Now of course this is a bit of a boring simulation to see something interesting happen we would need at least two objects, and preferably much more. Now we can duplicate the code a couple of times but I believe that you should never have to write the same code twice. Delete the following lines.

The line that starts with spriteBatch.Draw(…) in your Draw method

The members unitToPixel and pixelToUnit

The body member and everything that involves the body in the LoadContent method.

Now create a new class called DrawablePhysicsObject. This class will be a wrapper around a body object. We will automatically convert between pixel coordinates and the coordinates used by Farseer and we will make drawing a bit easier. Since there are no new concepts introduced in this class I’ll just place the code right here:

You see that we create one DrawablePhysicsObject with a Static BodyType. That’s going to be our floor. We also create a list of crates and do some keyboard logic. Lets create a method to fill that list of crates. Add this method to Game1.cs

A scripting engine is a useful component in any game-engine. It allows you to execute modified code (aka scripts) in real time while your game is running. This gives you immediate feedback, allows for easy debugging of scripts and gives you true rapid prototyping abilities.

Scripting engines are also easier to work with than a full blown programming language, an error in a script is easy to recover from and because the scripts aren’t compiled it’s easy for the script interpreter to give helpful debug information. Even better: you don’t have to compile the script and the game keeps running so immediately after you fix the bug in your script you can see the result.

Script engines gives opportunities for ‘other’-programmers (gameplay, leveldesign, animator, etc..), they might not wish to delve into the intricacies of the programming language and frameworks you’re using for the game engine but they will be more than willing to write some script to modify the behavior of that new enemy.

So, why write a scripting engine for XNA? Well after reading the article ‘Embracing Dynamism’ by Niklas Frykholm on #AltDevBlogADay I got interested again in scripting engines. Shortly after that I heard that someone wrote a full JavaScript interpreter for C# called JINT , well 1 + 1 = 2 so I started working on integrating JINT into XNA and see if I could set up an external IDE in WPF that, while the game is running, could load, modify and execute script code. After a few tries I finally succeeded and I’m pretty proud of the result.

All the wrapping and magic happens in the JintXNA project. The code, as it is now, works fine on Windows but Windows Phone and Xbox 360 support isn’t there yet out of the box since JINT is targeted at the full .NET 4.0 framework. However there is a port of JINT which targets the .NET Compact Framework which should run on WP7 and the 360, I haven’t tried this yet though.

You can download the full source code of JintXNA here this package includes the JintXNA project, the IDE and a sample project and script as seen in the video.

Nathan Bixel has written a short guide on how to add your models to Catalin Zima’s deferred rendering engine (my XNA 4 port is located here). You can see his manual in this thread on the XNA Game Programming Adventures website. In case it goes down, I’ve also made a small PDF print of it:

Anaglyphs are images designed to give a 3D effect when viewed with special glasses, usually with red and blue (sometimes red and cyan) filters over the left and right eyes, respectively.[1]

Using anaglyphs we can make our game look real 3D through those cheap red/cyan 3D-glasses. Adding an anaglyph effect to your XNA game is fairly easy.

Basically we need to undertake the following steps:
-Draw our scene twice to separate render targets, with a slightly offset camera
-Use a shader and draw a full screen quad to blend the images and color coding the images for each eye

We need to extract all your drawing code (except base.Draw(..)) to a new method that as argument accepts a view matrix. Update your code so that the passed viewMatrix is used instead of your normal camera’s viewMatrix. Doing this will allow us to easily draw the scene twice with a slightly offset camera. You should now have something like this:

private void DrawForEye(Matrix viewMatrix)
{
//...
}

Now let’s first write the shader that is going to blend the images, create a new effect in your content project and paste in the following code:

The texture’s left and right will be the textures resulting from drawing the scene twice, slightly offset from each other. We use a sampler with POINT filters because the left and right textures are going to be exactly the same size as our final rendering.

The vertex shader is passed as input nothing more than the position and texture coordinate of the vertex, it doesn’t transform anything but it just directly passes to the pixel shader.

The pixel shader samples the textures for the left and right eye. The red channel is used to ‘encode’ the image for the right eye (the red is unfiltered by the cyan colored lens). The green and blue channel are taken from the image for the left eye (they are unfiltered by the red colored lens). You can look at this wikipedia entry for other color combinations in case you have different 3D-glasses.

Now that we have our effect we need to add 2 render targets, the effect and a quad renderer to our game class. (The Quad class is posted as a code snippet here and used as to render the final image).

Added these lines to the top of your game class.

RenderTarget2D leftEye;
RenderTarget2D rightEye;
Effect anaglyphEffect;
QuadRenderer quad;
//you can change this later to test different distances between the left and right eye viewpoint,
//the offset depends on the scale of your game, but small values seem to work best.
//I used 0.05 for a scene about 5x5x5 size.
float ammount = 0.05f;

Now we need to calculate two slightly offset view-matrices, draw the scene two times using these view-matrices and then combine them using our effect. To accomplish this write the following Draw method:

This quad renderer was already part of my conversion of Catalin Zima’s Deferred Rendering for XNA tutorial, but because I plan to use it in a tutorial I’m going to write later today here is a handy snippet for drawing a quad with texture coordinates in XNA. (You could use the SpriteBatch class for this, but as you all know the SB class tends to mess up your render state if you do not define all states correctly).

In XNA shaders are processed into Effect objects by the content pipeline. These effect objects are not really ‘first class citizens’ because, contrarily to most C# classes, these classes have a lot of loosely-typed features. To remedy this I’m going to show you how I wrap these effect objects into their own wrapper, when we see the differences I’ll explain the pros and cons of my approach.

For this tutorial we’re going to use a part of a shader I use for deferred rendering:

Given the rest of the code is correct this will compile nicely, however during runtime we will receive an exception. Because we set the effect parameter “texture” to 56, which is not a proper texture value. Due to the loose typing this error could not be detected by the compiler, so it could sneak up on us. Also it’s a bit hard to remember all the parameters an effect has, because we cant see that without opening the .fx file, I’d argue that the effect class is not a proper class as we know other classes to be in C#. And it can’t be, because it has to be compatible with so many different shaders. Therefor I push forward my approach.

In my opinion this is a lot more readable and we now get an error while compiling that 56 does not match the type “Texture” also the new wrapper is more of an interface for the effect file. If we change one of the variable names in the effect file, we now only have to make a change at one place in our code base, even if we change the type of a parameter using some logic in the property we might still not have to change all the code. And if we really have to we will get a lot of helpful compiler warnings. We can now also find all references to a specific parameter. However the big downside is that Effect works for all effects (well you still have to remember the parameters and techniques which differ per shader), and this approach requires you to write a class per shader.

Anyway this is my approach, I’d love to know how other people handle this problem, and if you have any comments.

Update 7-2-2011:
After discussing alternative approaches (thanks Flashed!) I would like to give everybody a tip to try an extend this system. How about have a content pipeline project that automatically matches an effect file with an effect wrapper? You can use metadata in the .fx files todo this!