How to draw stuff at the correct place while using Farseer

Jan 31, 2011 at 4:27 PM

I have an issue while trying to draw images to the screen while using farseer.

I have everything set up, with a rectangle drawing at the same size as I set my Rectangle fixture.

However when I test collisions, the drawing is WAY off, and I fall through the drawn rectangle, but collide when I'm slightly off and up.

Can anyone give me a hand with trying to draw at the right position using the Farseer engine? I don't really want to use the debug draw thing included with the samples

Jan 31, 2011 at 8:18 PM

Take a look at the HelloWorld sample in the source control. It uses the Spritebatch for drawing textures.

You need to scale your physics world to use the MKS (Meter-Kilogram-Second) system. When you draw textures using the spritebatch, you need to convert the world units (meters) to screen units (pixels) in order for it to draw correctly.

Jan 31, 2011 at 8:22 PM

Alright, I'll have a look, but doesn't that used the debug view thing? Or can I set it up to work with my 2D Cameras matrix instead. The debugview thing is what really puts me off of messing with it

Jan 31, 2011 at 8:35 PM
Edited Jan 31, 2011 at 8:36 PM

The one in the source control uses the Spritebatch with a view matrix. Remember, if you need a camera, you can find one inside the DemoBaseXNA project - it is designed to use matrices for both view and projection - to use it with the spritebatch, you simply need to use Camera2D.ConvertWorldToScreen() to convert the body position (in meters) to texture position (in pixels). You also need to scale the texture correctly.

Edit: Oh, and it does use the debug view, but you can simply remove it if you don't need it.

Jan 31, 2011 at 9:06 PM

I just imported the Camera 2D into my project, and I'll see how it works. What sort of scaling factor do you recommend? If the texture is the same size in pixels as it was in meters, will it appear smaller?

Jan 31, 2011 at 9:31 PM

I ran into this problem of aligning textures with physics shapes.

Here is a link to a thread I started, not too long ago:

My basic approach was: GameObjects and everything is in world coordinate system using Farseer's MKS. I use the physic's body position to draw textures.

I setup a BasicEffect and ask Spritebatch to use that for rendering. The basiceffect has View and Orthographic projection matrices setup in a way, that overrides the default system. The default system assumes top-left corner as the (0,0), but Farseer Coordinate system (0,0) would be in the center of the screen. You need to account for that one way or another.

Once I tell Spritebatch to use the specific projection matrices, everything is in MKS, I need to scale the textures accordingly, otherwise things would be out of proportion. For e.g. Your rectangle shape is 6 m in width, but your texture is 32 x 32, and you were to place it as-is, the texture would be huge, since it implies the texture is 32 m x 32 m. Thus, 6/32 = 0.1875f would be the scale factor which would align texture with that rectangle, pixel perfect.


Hope it helped

Feb 2, 2011 at 9:53 AM
Edited Feb 2, 2011 at 10:18 AM

I'm having the same issue, spent hours reading the forum, and googling, none of the many solutions I've found have worked.. (I used FP2.x with no issues..)

Can we please get a simple example along the lines of...

public class Game1
Fixture Fixture;
Texture2D Texture;

protected override void LoadContent()
Texture = Content.Load<Texture2D>("MyTexture");
Fixture = FixtureFactory.CreateRectangle(Screen.World, Texture.Width, Texture.Height, 1.0f);
Fixture.Body.BodyType = BodyType.Dynamic;

protected override void Update(GameTime gameTime)

//We update the world


protected override void Draw(GameTime gameTime)

sb.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, null, Camera2D.Projection);

// This data is mostly from my animations, I was too lazy to write something else for this example..
sb.Draw(Texture, Camera2D.ConvertWorldToScreen(Body.Body.Position + a.Frames[CFrame].Offset), a.Frames[CFrame].FrameData, Color.White, 0.0f, new Vector2(a.Frames[CFrame].FrameData.Width / 2, a.Frames[CFrame].FrameData.Height / 2), Scale, SpriteEffects.None, 0);



Just something to show me how to use the Camera2D class you provided, with the spritebatch, and make it actually draw my "custom" texture where I need it to be.. (If it exist in either the Hello World sample, or SimpleSamples, etc, I could not find it.. I used Find, and F3'd the whole project..)

I've tried everything, I even ripped my engines guts out, and spliced yours in(SimpleSamples), hoping that would work, but it didn't.. (Though, your stuff worked fine like that, ie, Demo1-9..)

PS: I'm not trying to sound rude or anything, ppl tend to get that impression from me, I'm just annoyed, and haven't slept right, in forever(like 4 hours a night.. for months..), plus I'm about 20 hours in today.... (I swear, I'm going to end up like that dude from Fight Club..)

Feb 2, 2011 at 10:32 AM

The updated HelloWorld XNA sample uses the SpriteBatch and its use is not burried at all. It is however only in the source control and not yet in the downloads section, which has been stated in numerous discussions here though. I guess we should change that soonish... :/

Usage of the Camera2D class will not work  without adapting it a bit in most cases. HelloWorld XNA provides minimal camera functionality without it. A new camera class will most likely be present in the 3.3 release. The SimpleSamples use primitives instead of spritebatch for rendering. That will also change, but for now it may not be the best example if you start out with 3.x


Feb 2, 2011 at 11:41 AM
Edited Feb 2, 2011 at 11:48 AM

Judging by the amount of these topics, etc, it would probably be good to get that sample up, or else I see no end to these kinds of questions\topics..

So how bout my suggestion, a simple example in the format I suggested, using a matrix setup, should be fine, I can build the camera class myself, once I have an idea of what I'm trying to build.. (Simply fill the above game class with the basics of a single rectangle fixture, and get it drawing using a matrix\spritebatch..)

Anyways, thanks for answering me, and for working on this project, etc,.. :) It would be greatly appreciated if I could get that example soon, my engine is pretty much on hold, because everything is going to use Farseer, my animation editor(for attaching bodies to frames, it should be easier to handle this way..), my level editor(for previews, etc,..), and my game engine itself. (I have some little misc stuff I can do, but nothing I can't rip through in a few hours...)

(Again, I hope I didn't come off as rude, it's not my intention...)

Feb 2, 2011 at 12:31 PM
Edited Feb 2, 2011 at 12:31 PM

That sample you suggest already exists. Just browse to "Source Code" on the top. Goto "Latest Version -> Browse" on the left. From there to "Samples -> HelloWorldXNA".

Either download the whole project or just have a look at Game1.cs. It contains exactly what you are looking for and it won't get any simpler than that.

If you want to compile the new sample you probably have to specify the correct path to the DebugView, Farseer etc. but that is just a matter of openening it in VS 20xx and setting the path / references to your local files.

Feb 2, 2011 at 8:05 PM
Edited Feb 3, 2011 at 2:57 AM

Thanks, that looks like it does exactly what I needed, hopefully, I can get it integrated into my game\etc today, I'm anxious to get it working... :)

(I had a fully completed engine using FP2.x, but, it was lost during an HD failure, so really, I'm just rushing to put it back together, namely, while it's all still fresh in my mind.. Lot's to do, and to remember, etc,..)


That didn't work, it was further off than my own attempts, I'll try some more, but I don't think I did anything wrong, seeing as I mainly copied\pasted the stuff in....


Feb 3, 2011 at 6:15 AM
Edited Feb 3, 2011 at 6:34 AM

I still can't get this to work, I downloaded the source control version, it compiles and runs fine, so can anyone see what I'm doing wrong here.. I've looked this over several times, and it looks the same as your version... This is built on top of your sample stuff(screenmanager, etc,..)... The only thing I can think of is that something else is interfering with it...

(I added a DisplayUnits field to ConvertUnits, it stores the value set in ConvertUnits.SetDisplayUnitToSimUnitRatio, so that's why that's there....)


using System.Text;
using FarseerPhysics.DebugViews;
using FarseerPhysics.DemoBaseXNA;
using FarseerPhysics.DemoBaseXNA.DemoShare;
using FarseerPhysics.DemoBaseXNA.ScreenSystem;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Input;

namespace GameEngine
internal class TestScreen : PhysicsGameScreen, IDemoScreen

#region IDemoScreen Members

public string GetTitle()
return "Test Screen";

public string GetDetails()
StringBuilder sb = new StringBuilder();
sb.AppendLine("Test screen... For testing....");
return sb.ToString();


private Fixture _groundFixture;
private Texture2D _groundSprite;

private Matrix _projection;
private Matrix _view;
private Matrix _viewDebug;

private Vector2 _cameraPosition;
private Vector2 _screenCenter;
private float _cameraRotation;

public override void LoadContent()

  World = new World(new Vector2(0, -20));

// The DebugView needs a projection matrix with the screen size in meters
_projection = Matrix.CreateOrthographicOffCenter(0f, ScreenManager.GraphicsDevice.Viewport.Width / ConvertUnits.DisplayUnits,
ScreenManager.GraphicsDevice.Viewport.Height / ConvertUnits.DisplayUnits, 0f, 0f, 1f);
// Initialize camera controls
_view = Matrix.Identity;
_viewDebug = Matrix.Identity;
_cameraPosition = Vector2.Zero;
_cameraRotation = 0f;

_screenCenter = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width / 2f,
ScreenManager.GraphicsDevice.Viewport.Height / 2f);

_groundSprite = ScreenManager.ContentManager.Load<Texture2D>("Materials/Waves"); // 512px x 64px => 8m x 1m

/* Ground Fixture: */
Vector2 groundPosition = _screenCenter / ConvertUnits.DisplayUnits + Vector2.UnitY * 1.25f;

// Create the ground fixture
_groundFixture = FixtureFactory.CreateRectangle(World, _groundSprite.Width / ConvertUnits.DisplayUnits, _groundSprite.Height / ConvertUnits.DisplayUnits, 1f, groundPosition);
_groundFixture.Body.IsStatic = true;

_groundFixture.Restitution = 0.3f;
_groundFixture.Friction = 0.5f;

public override void HandleGamePadInput(InputHelper input)

public override void HandleKeyboardInput(InputHelper input)

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
_view = Matrix.CreateTranslation(new Vector3(_cameraPosition - _screenCenter, 0f)) *
Matrix.CreateRotationZ(_cameraRotation) *
Matrix.CreateTranslation(new Vector3(_screenCenter, 0f));

base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
public override void Draw(GameTime gameTime)
/* Ground position and origin */
Vector2 groundPos = _groundFixture.Body.Position * ConvertUnits.DisplayUnits;
Vector2 groundOrigin = new Vector2(_groundSprite.Width / 2f, _groundSprite.Height / 2f);

ScreenManager.SpriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, _view);
ScreenManager.SpriteBatch.Draw(_groundSprite, groundPos, null, Color.White, 0, groundOrigin, 1, SpriteEffects.None, 0);



Edit: I went through, and debugged this, all the values seem to be correct, screen size, DisplayUnits, all the events fired properly, so something is definitely not right.. Whether I'm overlooking something stupid, or it's a bug, I have no clue.... I also tried that same texture in the Hello World sample, to verify it wasn't something like that, it wasn't, the texture doesn't matter..

Feb 3, 2011 at 9:46 AM

The code looks correct, so my guess would be that your problem is somewhere else. If it is not to big and you could somehow send me your project I will have a look at it.

What parts of the ScreenManager are you using?

The ScreenManager does some fancy render target magic for screen transitions. You have to be careful about the drawing order of your screens, cause everything drawn prior to a render target change is lost cause the graphics cards just discards it.

Feb 3, 2011 at 10:03 AM
Edited Feb 3, 2011 at 10:46 AM

I'm using the entire simple samples project for my engine until I get everything sorted with FPE3..

Since I wasn't clear, it is rendering, it's just rendering in the wrong place(and the scaling is wrong..), while the Hello World sample using the same texture worked as expected.. (So I don't think it's platform specific.. ie, Win7 x64..)

I could send it to you, however, if you add that class into the simple samples as a new screen it should give you the same setup as me...(I have the one from the downloads screen..) You just need to make this change to ConvertUnits..

        private static float _displayUnitsToSimUnitsRatio = 100;
        public static float DisplayUnits
            get { return _displayUnitsToSimUnitsRatio; }


Edit: Here in case you need it.. It's only 2.42mb..

I'm heading to bed, I hope you have better luck than me.. Been about to tear my hair out on this one..

Feb 3, 2011 at 11:28 AM

Your code is perfectly fine and your object is created exactly where you want it to be. What you don't do however is draw the debug view properly. The PhysicsGameScreen is tuned for the samples. The ScreenManager has its own Camera which uses its own custom coordinate system in which the DebugView is drawn. Unfortunately this custom coordinate system has nothing to do with the one you use for drawing your stuff, that is why they don't align properly. Either you set up the ScreenManagers camera to use the same projection you use for drawing your stuff... or you draw the DebugView yourself like it is done in the samples, as you don't use the ScreenManagers camera anyway at the moment.

Farseer 3.3 will have new samples with a camera that automatically adapts to your projection... for now it doesn't and you can't expect the DebugView to align itself to your drawing :/

On a side note: If you mess around with the camera in its current state, you will also have to adapt the Border object. The samples work with an orthographic projection that is resolution independent and always has the same scale, that is objects always cover the same portion of the screen but may therefore vary in pixel size. I guess you want objects with a fixed pixel size, which get smaler if you crank up the resolution in terms of screen space covered.

Feb 3, 2011 at 10:02 PM

Ok, that makes sense, I was going crazy over here, because I knew my code was right, as far as drawing my stuff went..

I didn't even think of the possibility that the debug object was being drawn in the wrong place.. :)

Hopefully I can get it working now, thanks for the help.

Feb 4, 2011 at 2:22 AM
Edited Feb 4, 2011 at 2:23 AM

I made a number of changes to the FarseerLib itself, to make using the MKS system less of a hassle... I don't know if you can do this in the main project without causing issues, but I figured I would list the changes..

In the world class, I did this..


        // MKS Units 
public static float Units;
public World(Vector2 gravity, float units = 0) { World.Units = units; Snip....


This also lets me call World.Units anytime I need my unit number.. Then, I went into the FixtureFactory, and added this...


        // MKS System Added
        public static Fixture CreateRectangle(World world, float width, float height, float density)
            if (World.Units != 0)
                return CreateRectangle(world, width / World.Units, height / World.Units, density, null);
                return CreateRectangle(world, width, height, density, null);


Then I went into the body class and did this..


        public Vector2 Position
                if (World.Units != 0)
                    return Xf.Position * World.Units;
                    return Xf.Position; 
            set { SetTransform(ref value, Rotation); }



Now I when I create my world I can just set the c# 4.0 optional parameter "units", and if I do, it will take care of the math behind the scenes for me... I still have to use it in several places myself, but if I keep applying this method, I'm sure I can cut it down to where the MKS system is nearly transparent..

Anyways, I got my project going now, thanks for all the help.