在farseer物理引擎的body.cs中,“nullreferenceexception未处理”

时间:2011-10-06 01:03:16

标签: c# xna xna-4.0 farseer

我是一名尝试c#的c ++程序员。我用c ++中的box2d做了很多,但这是我第一次使用c#。所以,我正在尝试使用更小的物理引擎制作一个简单的游戏。当我尝试编译我的代码时(我正在使用visual studio c#2010 express和xna game studio 4.0),它会在IBroadPhase broadPhase = World.ContactManager.BroadPhase;的body.cs中停止。出现此错误:nullreferenceexception was unhandled。我相信问题出在我的Player类中,所以这里是代码:

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);
    }
}

farseer测试平台运行正常,所以我很确定我的代码是问题,而不是更狡猾。如果您需要查看更多我的代码,请告诉我们。我也在这个论坛上发布了这个,所以如果我在那里得到答案,我会让你们知道。提前谢谢。

1 个答案:

答案 0 :(得分:0)

有人让我展示Game1.cs的代码,并发现了问题。问题是我在初始化播放器之前从未构建过世界。在我初始化播放器之前添加world = new World(Vector2.Zero);来修复它。