55 months of blogging: some statistics

Fifty-five months ago I thought I had a brilliant idea for XNA’s ContentManager so I opened a blog on www.wordpress.com. A few hours later my thoughts of brilliance were shattered when someone told me the improvements I made were already there (hidden from view). Anyway I decided to continue writing tutorials and technical articles. A few years later I moved the entire blog to http://roy-t.nl where it is now. Today I was studying for a course on statistical pattern recognition. This got me thinking. Except for sometimes tallying up all the views I hadn’t done any analysis of the total impact on the internet I made. Of course it’s just a drop in the ocean, but I’m pretty pleased. The statistics:

Total views: 259.587, which averages nearly 5000 a month, in this month I expect over 6000 views

Total comments: 435, nearly 8 a month (OK that is not too much, but as a tutorial site most people just hit and run!)

Total posts: 120 (including this one), averaging  a bit over 2 a month. Currently I aim at one post per month but some months its hard to keep up!

Income from adds and donations: E 70,- (A long time ago I removed the donation button and the adds)

Total video views: 22.289, or 4397 minutes

Awards won: 1 (2nd place in the SgtConker XNA Tutorial contest)

Offers to write a book received: 2 (Not kidding, publishers approached me to write introductory books about XNA 4, unfortunately I didn’t had the time to write one, and I’m not 100% sure I’m qualified enough)

 

 

27
Jan 2013
CATEGORY

Blog

COMMENTS 4 Comments

Farseer physics 3.3.1 and XNA: Platformer character

It took a while, but here I finaly present you the third and final part of the Farseer Physics 3.3.1 and XNA tutorial series!

Part 1 of this tutorial
Part 2 of this tutorial

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

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:

/// <summary>
/// Creates a circular drawable physics object
/// </summary>
/// <param name="world">The farseer simulation this object should be part of</param>
/// <param name="texture">The image that will be drawn at the place of the body</param>
/// <param name="diameter"> The diameter in pixels</param>
/// <param name="mass">The mass in kilograms</param>
public DrawablePhysicsObject(World world, Texture2D texture, float diameter, float mass)
{
    size = new Vector2(diameter, diameter);
    Body = BodyFactory.CreateCircle(world, (diameter / 2.0f) * CoordinateHelper.pixelToUnit, 1);

    Body.BodyType = BodyType.Dynamic;

    this.Size = size;
    this.texture = texture;
}

And to fix the drawing code replace the draw method in the DrawablePhysicsObject class with this one

public void Draw(SpriteBatch spriteBatch)
{            
	Rectangle destination = new Rectangle
	(
		(int)Position.X,
		(int)Position.Y,
		(int)Size.X,
		(int)Size.Y
	);

	spriteBatch.Draw(texture, destination, null, Color.White, Body.Rotation, new Vector2(texture.Width / 2.0f, texture.Height / 2.0f), SpriteEffects.None, 0);
}

Now we can start with the player character. Add a new class to your project called Player and add the following private fields and constructor

private DrawablePhysicsObject torso;
private DrawablePhysicsObject wheel;
private RevoluteJoint axis;

public Player(World world, Texture2D torsoTexture, Texture2D wheelTexture, Vector2 size, float mass, Vector2 startPosition)

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!)

Vector2 torsoSize = new Vector2(size.X, size.Y - size.X / 2.0f);
float wheelSize = size.X;

// Create the torso
torso = new DrawablePhysicsObject(world, torsoTexture, torsoSize, mass / 2.0f);
torso.Position = startPosition;            
			
// Create the feet of the body
wheel = new DrawablePhysicsObject(world, wheelTexture, wheelSize, mass / 2.0f);
wheel.Position = torso.Position + new Vector2(0, torsoSize.Y / 2.0f);

Now we can start adding joints. We will use a Fixed Angle Joint to keep the torso straight up at all times and we use a Revolute Joint to move the wheel (feet) of the character.

// Create a joint to keep the torso upright
JointFactory.CreateFixedAngleJoint(world, torso.Body);

// Connect the feet to the torso
axis = JointFactory.CreateRevoluteJoint(world, torso.Body, wheel.Body, Vector2.Zero);
axis.CollideConnected = false;
            
axis.MotorEnabled = true;
axis.MotorSpeed = 0;
axis.MotorTorque = 3;
axis.MaxMotorTorque = 10;

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.

public void Draw(SpriteBatch spriteBatch)
{
	torso.Draw(spriteBatch);
	wheel.Draw(spriteBatch);
}

Great! Let’s go to game class, add a field for the player, load it, and make it visible!

public class Game1
{
	...
	
	Player player;
	
	...
	
	protected override void LoadContent()
	{
		...
		
		player = new Player
            (
                world,
                Content.Load<Texture2D>("Player"),
                Content.Load<Texture2D>("Wheel"),
                new Vector2(20, 75),
                100,
                new Vector2(430, 0)
            );     		
	}
	
	...
	
	protected override void Draw(GameTime gameTime)
	{
		...
		
		player.Draw(spriteBatch);
		
		...
	}
}

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:

public enum Movement
{
    Left,
    Right,
    Stop
}

Add the following code to your player class:

float speed = 3.0f;

...

public void Move(Movement movement)
{
	switch(movement)
	{
		case Movement.Left:
			axis.MotorSpeed = -MathHelper.TwoPi * speed;
			break;

		case Movement.Right:
			axis.MotorSpeed = MathHelper.TwoPi * speed;
			break;

		case Movement.Stop:                    
			axis.MotorSpeed = 0;
			break;
	}
}

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:

private DateTime previousJump = DateTime.Now;   // time at which we previously jumped
private const float jumpInterval = 1.0f;        // in seconds
private Vector2 jumpForce = new Vector2(0, -1); // applied force when jumping

public void Jump()
{
	if ((DateTime.Now - previousJump).TotalSeconds >= jumpInterval)
	{
		torso.Body.ApplyLinearImpulse(ref jumpForce);
		previousJump = DateTime.Now;
	}
}

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.

if (keyboardState.IsKeyDown(Keys.LeftControl) && !prevKeyboardState.IsKeyDown(Keys.LeftControl))
{
    player.Jump();
}

Et voila! We have a controllable player character which you can use in your very own platform game! Fire up your game and if you followed my instructions this is what you should end up with:

You can download the complete source code (includes everything from the previous two tutorials and this one) here

Fun trivia

  • I published (and wrote most) of this tutorial on my birthday, 25 now, yay!
  • In 2010 I got 2nd place on SgtConker’s Absolutely Fine tutorial contest writhing the Farseer 2.x version of this series
02
Jan 2013
COMMENTS 12 Comments

Facial Feature Detection, the result

So in this post you saw me playing with facial feature detection. I’ve used that to construct a robot (together with Ynze van der Spek) that tries to mimic your facial expressions, the robot was inspired on the MIMBO project, since ours ran on Windows instead of on an iPhone we’ve called it Wimbo. The robot was part of an exhibit at the Rijksuniversiteit Groningen for 2 months and was then moved to Der Aa-Kerk in Groningen for the ‘Nacht van de Kunst en Wetenschap‘  (Night of Arts & Sciences). My old boss just e-mailed me some pictures of the robot in use during the exhibit so I’d thought I’d share them.

Wimbo was build for Science LinX, an institute of the faculty of Natural Sciences at the Rijksuniversiteit Groningen that tries to inspire pupils to choose a career in science. The photos were made by Hugomatic

 

 

Btw, as you see this is not the third, and final, Farseer Physics tutorial, unfortunately I haven’t had much time to program on personal projects lately, but I promise I will try to finish it as soon as I can. Can’t give any ETAs though!

25
Oct 2012
CATEGORY

Blog, Personal

COMMENTS No Comments
TAGS

C# Asynchronous sockets revisited

Three years ago I wrote a quick code snippet explaining asynchronous sockets. Recently someone found a rather large bug in that code so I decided to rewrite the tutorial (it’s one of my more popular articles and people have long been asking for the source code, which I lost a few years ago. So this way I kill a bug and give people the source code all at once).

I would like to thank stackoverflow user Polity for notifying me of the problems.

The client

Let’s first start with the client. For this example I created a small console application. It reads lines from the console until it sees an empty line. The text is then converted to a byte[] using the UTF8-Encoding schema.  Meanwhile I create a socket and call the BeginConnect method to start the process of creating an asynchronous connection. Asynchronous in this regards means that the entire program can keep crushing while a separate thread setups up the connection and sends the data. To guide the setup and the sending of the data while the program is running several callbacks are used. One to finish the connection setup and one to send the actual data. Before the actual message is sent I first send 4 bytes to tell how long the message is going to be. (Not doing this caused a subtle bug in the previous version which assumed a message was done once the receive buffer of the server was not entirely filled).

The server

The server is also simple. There is one socket continuously accepting new connections. So in contrary to the previous version this version accepts multiple concurrent connections. Once a connection has been made a separate thread is spawned, implicitly, by using the asynchronous BeginAccept method. In a callback the connecting is accepted using a new socket so the server can keep listing for more connections on the old socket. For each connection a small state object is kept to do the bookkeeping. It stores the active socket, the buffer, and fields  with information about the amount of data we expect to receive and how much data we have indeed received. In the read callback the first 4 bytes are extracted so that we know how much data to accept. After that we keep using BeginReceive until all data has made it’s way to the server. Only then we reconstruct the message.

Note that I use the TCP protocol for the sockets so I know that the data will be complete and in-order.

The source code

I’ve created a Visual Studio 2012 solution with the above two projects in them. Everything is compiled using the .NET 4.5 framework. The example will probably also compile in .NET3.5 but I noticed some methods that I previously used were deprecated  in .NET4.5, so I’ve used alternatives that might no be available in .NET3.5 (should be trivial to fix).

You can find the source code here

09
Sep 2012
CATEGORY

Blog, Programming

COMMENTS 5 Comments

Farseer physics 3.3.1 and XNA: Joints

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

Enforces that two bodies can only slide in a linear motion (one degree of freedom) with respect to each other. See http://en.wikipedia.org/wiki/Prismatic_joint

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.

Create this new helper class:

    public static class CoordinateHelper
    {
        // Because Farseer uses 1 unit = 1 meter we need to convert
        // between pixel coordinates and physics coordinates.
        // I've chosen to use the rule that 100 pixels is one meter.
        // We have to take care to convert between these two
        // coordinate-sets wherever we mix them!

        public const float unitToPixel = 100.0f;
        public const float pixelToUnit = 1 / unitToPixel;

        public static Vector2 ToScreen(Vector2 worldCoordinates)
        {
            return worldCoordinates * unitToPixel;
        }

        public static Vector2 ToWorld(Vector2 screenCoordinates)
        {
            return screenCoordinates * pixelToUnit;
        }
    }

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:

List paddles;

Then add the following three lines to draw the paddles:

foreach (DrawablePhysicsObject paddle in paddles)
{
    paddle.Draw(spriteBatch);
}

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:

// Create a simple paddle which center is anchored
// in the background. It can rotate freely
DrawablePhysicsObject simplePaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

JointFactory.CreateFixedRevoluteJoint
(
    world,
    simplePaddle.body,
    CoordinateHelper.ToWorld(new Vector2(0, 0)),
    CoordinateHelper.ToWorld(new Vector2(GraphicsDevice.Viewport.Width / 2.0f - 150,
                                         GraphicsDevice.Viewport.Height - 300))
);

paddles.Add(simplePaddle);

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.

A motorized joint

The motorized joint is very similar:

// Creates a motorized paddle which left side is anchored in the background
// it will rotate slowly but the motor is not set soo strong that
// it can push everything away.
DrawablePhysicsObject motorPaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

var j = JointFactory.CreateFixedRevoluteJoint
(
    world,
    motorPaddle.body,
    CoordinateHelper.ToWorld(new Vector2(-48, 0)),
    CoordinateHelper.ToWorld(new Vector2(GraphicsDevice.Viewport.Width / 2.0f,
                                         GraphicsDevice.Viewport.Height - 280))
);

// rotate 1/4 of a circle per second
j.MotorSpeed = MathHelper.PiOver2;
// have little torque (power) so it can push away a few blocks
j.MotorTorque = 3;
j.MotorEnabled = true;
j.MaxMotorTorque = 10;

paddles.Add(motorPaddle);

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:

// Use two line joints (a sort of springs) to create a trampoline
DrawablePhysicsObject trampolinePaddle = new DrawablePhysicsObject
(
    world,
    Content.Load("Paddle"),
    new Vector2(128, 16),
    10
);

trampolinePaddle.Position = new Vector2(600, floor.Position.Y - 175);

var l = JointFactory.CreateLineJoint
(
    floor.body,
    trampolinePaddle.body,
    CoordinateHelper.ToWorld(trampolinePaddle.Position - new Vector2(64, 0)),
    Vector2.UnitY
);

l.CollideConnected = true;
l.Frequency = 2.0f;
l.DampingRatio = 0.05f;

var r = JointFactory.CreateLineJoint
(
    floor.body,
    trampolinePaddle.body,
    CoordinateHelper.ToWorld(trampolinePaddle.Position + new Vector2(64, 0)),
    Vector2.UnitY
);

r.CollideConnected = true;
r.Frequency = 2.0f;
r.DampingRatio = 0.05f;

world.AddJoint(l);
world.AddJoint(r);

paddles.Add(trampolinePaddle);

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.

06
Sep 2012
COMMENTS 11 Comments
TAGS

, , ,

Big website renovation coming up!

So this website is starting to feel really dated, the shades of gray are from another era. The text is too wide when seen on a high-resolution wide screen displays and there is way too much clutter. Tag clouds, donate buttons, stack overflow profiles, adds, recent comments etc.. etc… Unfortunately I’m a terrible designer, a hoarder of features, and I can’t tell if two colours complement or conflict. But luckily my ‘little’ brother is the exact opposite. He has his own design company called Label 90 and has agreed to give the website a nice make-over. To not make his job too difficult he asked me to pick a theme that I licked (In the end I choose this one) and started from there. With nothing more than the starting theme and a few screenshots from stuff I liked he created something quite wonderful.

In the next few days I will (finish) converting the website to the new theme. As a reference here is an image of how the website looked the last four years (from August 2008 till August 2012).


(clickable)

02
Sep 2012
CATEGORY

Blog

COMMENTS No Comments
TAGS

Farseer physics 3.3.1 and XNA

Part 2
Part 3

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

Body body;
const float unitToPixel = 100.0f;
const float pixelToUnit = 1 / unitToPixel;

And add the following code at end of the LoadContent method

Vector2 size = new Vector2(50, 50);
body = BodyFactory.CreateRectangle(world, size.X * pixelToUnit, size.Y * pixelToUnit, 1);
body.BodyType = BodyType.Dynamic;
body.Position = new Vector2((GraphicsDevice.Viewport.Width / 2.0f) * pixelToUnit, 0);

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

spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque);
Vector2 position = body.Position * unitToPixel;
Vector2 scale = new Vector2(50 / (float)texture.Width, 50 / (float)texture.Height);
spriteBatch.Draw(texture, position, null, Color.White, body.Rotation, new Vector2(texture.Width / 2.0f, texture.Height / 2.0f), scale, SpriteEffects.None, 0);
spriteBatch.End();

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:

public class DrawablePhysicsObject
    {
        // Because Farseer uses 1 unit = 1 meter we need to convert
        // between pixel coordinates and physics coordinates.
        // I've chosen to use the rule that 100 pixels is one meter.
        // We have to take care to convert between these two
        // coordinate-sets wherever we mix them!

        public const float unitToPixel = 100.0f;
        public const float pixelToUnit = 1 / unitToPixel;

        public Body body;
        public Vector2 Position
        {
            get { return body.Position * unitToPixel; }
            set { body.Position = value * pixelToUnit; }
        }

        public Texture2D texture;

        private Vector2 size;
        public Vector2 Size
        {
            get { return size * unitToPixel; }
            set { size = value * pixelToUnit; }
        }

        ///The farseer simulation this object should be part of
        ///The image that will be drawn at the place of the body
        ///The size in pixels
        ///The mass in kilograms
        public DrawablePhysicsObject(World world, Texture2D texture, Vector2 size, float mass)
        {
            body = BodyFactory.CreateRectangle(world, size.X * pixelToUnit, size.Y * pixelToUnit, 1);
            body.BodyType = BodyType.Dynamic;

            this.Size = size;
            this.texture = texture;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            Vector2 scale = new Vector2(Size.X / (float)texture.Width, Size.Y / (float)texture.Height);
            spriteBatch.Draw(texture, Position, null, Color.White, body.Rotation, new Vector2(texture.Width / 2.0f, texture.Height / 2.0f), scale, SpriteEffects.None, 0);
        }
    }
}

Now lets set this code to work!
Create the following members in Game1.cs

List<DrawablePhysicsObject> crateList;
DrawablePhysicsObject floor;
KeyboardState prevKeyboardState;
Random random;

And add this line to the end of the LoadContent method.

random = new Random();

floor = new DrawablePhysicsObject(world, Content.Load("Floor"), new Vector2(GraphicsDevice.Viewport.Width, 100.0f), 1000);
            floor.Position = new Vector2(GraphicsDevice.Viewport.Width / 2.0f, GraphicsDevice.Viewport.Height - 50);
floor.body.BodyType = BodyType.Static;
crateList = new List<DrawablePhysicsObject>();
prevKeyboardState = Keyboard.GetState();

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

private void SpawnCrate()
{
	DrawablePhysicsObject crate;
	crate = new DrawablePhysicsObject(world, Content.Load<Texture2D>("Crate"), new Vector2(50.0f, 50.0f), 0.1f);
	crate.Position = new Vector2(random.Next(50, GraphicsDevice.Viewport.Width - 50), 1);

	crateList.Add(crate);
}

This method will spawn a random crate somewhere at the top of the screen. We will trigger this method by a pressing the spacebar. To do so add this to the update method before base.Update().

KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.Space) && !prevKeyboardState.IsKeyDown(Keys.Space))
{
    SpawnCrate();
}

prevKeyboardState = keyboardState;

And finally add these last few lines in between spriteBatch.Begin() and spriteBatch.End() in your draw method so that we can see what’s going on.

foreach (DrawablePhysicsObject crate in crateList)
{
    crate.Draw(spriteBatch);
}

floor.Draw(spriteBatch);

Run the simulation and start hammering on the spacebar you should see something like this:

This concludes this tutorial. In the next tutorial we will talk about springs and joints and ways to make compound bodies so that you can have more interesting simulations!

You can download the source code for this tutorial here: Farseer v3.3.1 XNA Tutorial 1

Thanks to Ryan Foy for pointing out some errors in the code that somehow made it onto this blog

19
Aug 2012
COMMENTS 12 Comments

Sgtconker.com becomes Madgamedev.com, some links broken

A few of my tutorials are posted on external websites, one of those website is www.sgtconker.com which was managed by @Conkerjo unfortunately updates were stagnating because the work pressure Conkerjo was under so the website is now under new management. ‘Mad Ninja Skillz’ the developer behind EZMuze has taken over management. To reflect this the website has been renamed MadGameDev.com. So… what does this mean for you?

Well unfortunately they are having problems forwarding the visitors from sgtconker.com to madgamedev.com so any links on this blog that link to articles and files on sgtconker.com are currently broken. However all the articles are there and available at madgamedev.com. If they can’t get the forwarding issue fixed within a week or so I’ll go through all the articles and fix the links myself, but since that would involve skimming through all links in 120 posts I’ll wait a bit to see if the situation will resolve itself.

27
Jul 2012
CATEGORY

Blog

COMMENTS No Comments

Thesis: upper sets in partially ordered sets

Today I finally finished my thesis. It’s topic was to count the number of upper sets in partially ordered sets Which is quite a hard problem since it’s in the complexity class #P-Complete (that’s the class of counting the solutions to the decision problems in NP-complete). All and all I’m quite pleased with the result. Although the upper bound is still O(2^{n}), (can’t quite get under there without solving P=NP and winning a million dollars) I’ve manged to find a solution that has a best case of O(n) both in time and memory complexity. With a particularly large data set the brute-force algorithm took over 2 hours to complete while my algorithm took 0.025 seconds. Now that’s what I’d call a speed gain (and yes it was a real life data set, no tricks here). You can see this for yourself in the graph at the bottom of this post the ‘naïeve algoritme’ is the brute force approach, the ‘Familiealgoritme zonder uptrie’ is the first version of my algorithm, the ‘Familiealgoritme met uptrie’ is the final version of my algorithm. It uses a trie like data structure to speed up searching and uses a lot less memory. Note that the graph has a logarithmic scale.

Unfortunately for most readers my thesis is in Dutch, but I’ve translated the abstract to English:

Counting the number of upper sets in partially ordered sets gives us a unique number that can be used to compare sets. This number is like the fingerprint of a set. Until now there isn’t, as to my knowledge, an efficient algorithm to calculate this number. This meant that the number had to be calculated either by hand or by using a brute force approach. Using a brute force approach leads quickly to problems, even for trivially small data sets since this means that you have to generate 2^n subsets and check each of these subsets on upwards closure. When calculating by hand you can use symmetry but this menial process can take a lot of time and is error prone. In this thesis I present an algorithm that can calculate exact, and usually fast, the number of upper sets in a partially ordered set.

You can download my thesis here: Upper sets in partially ordered sets (Bsc thesis Roy Triesscheijn) as I’ve said before the text is in Dutch, but the proofs and attached code should be readable enough. If you’ve got any questions feel free to ask below!

Thesis time benchmark

Using JavaScript as a script engine in XNA/C#

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.

05
Jun 2012
COMMENTS 1 Comment