Search code examples
c#xnaxna-4.0farseer

"nullreferenceexception was unhandled" in body.cs of farseer physics engine


I'm a c++ programmer trying out c#. I've done a lot with box2d in c++, but this is my first time with c#. So, I'm trying to make a simple game with farseer physics engine. When I try to compile my code (I'm using visual studio c# 2010 express and xna game studio 4.0), it stops in body.cs at IBroadPhase broadPhase = World.ContactManager.BroadPhase; With this error: nullreferenceexception was unhandled. I believe the problem is in my Player class, so here's the code for that:

public class Player : Entity
{
    Vector2 position;
    SpriteBatch spriteBatch;
    Texture2D texture;
    Rectangle rectangle;
    Body body;
    CircleShape shape;
    Fixture fixture;
    public Player()
    {
        // TODO: Construct any child components here
    }

    /// 
    /// Allows the game component to perform any initialization it needs to before starting
    /// to run.  This is where it can query for any required services and load content.
    /// 
    public override void Initialize(World world, SpriteBatch spriteBatch, Texture2D texture)
    {
        // TODO: Add your initialization code here
        this.spriteBatch = spriteBatch;
        this.texture = texture;
        rectangle = new Rectangle(0, 0, 11, 14);
        body = BodyFactory.CreateBody(world);
        body.BodyType = BodyType.Dynamic;
        body.Position = new Vector2(0, 0);
        shape = new CircleShape(1.0f, 1.0f);
        fixture = body.CreateFixture(shape);
        base.Initialize(world, spriteBatch, texture);
    }

    /// 
    /// Allows the game component to update itself.
    /// 
    /// <param name="gameTime" />Provides a snapshot of timing values.
    public override void Update(GameTime gameTime)
    {
        // TODO: Add your update code here

        base.Update(gameTime);
    }

    public override void Draw(GameTime gameTime)
    {
        spriteBatch.Begin();
        spriteBatch.Draw(texture, new Vector2(body.WorldCenter.X * 10, body.WorldCenter.Y * 10), rectangle, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }
}

The farseer testbed runs fine, so I'm pretty sure my code is the problem, and not farseer. Let me know if you need to see more of my code. I've also posted this in the farseer forums, so If I get an answer there, I'll let you guys know. Thanks in advance.


Solution

  • Someone asked me to show the code of Game1.cs, and found the problem. The problem was that I had never constructed the world before initializing my player. It was fixed by adding world = new World(Vector2.Zero); before I initialized the player.