nullreferenceexception未处理;在身体.cs的远见的物理引擎

本文关键字:远见 引擎 cs 未处理 nullreferenceexception | 更新日期: 2023-09-27 18:10:28

我是一个尝试c#的c++程序员。我用c++做过很多box2d,但这是我第一次用c#。所以,我尝试着用更长远的物理引擎去创造一款简单的游戏。当我尝试编译我的代码(我使用visual studio c# 2010 express和xna game studio 4.0)时,它在body.cs中停止在IBroadPhase broadPhase = World.ContactManager.BroadPhase;,此错误:nullreferenceexception was unhandled。我认为问题是在我的播放器类,所以这里的代码:

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测试平台运行良好,所以我很确定是我的代码出了问题,而不是farseer。如果您需要查看更多我的代码,请告诉我。我也在farseer论坛上发布了这个问题,所以如果我在那里得到了答案,我会告诉你们的。

nullreferenceexception未处理;在身体.cs的远见的物理引擎

有人让我展示Game1.cs的代码,发现了问题。问题在于,在初始化玩家之前,我从未构建过游戏世界。在我初始化玩家之前,通过添加world = new World(Vector2.Zero);来修复。