2011-10-06 34 views
1

我是一名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。我相信这个问题是在我的播放器类,所以这里的该代码:“nullreferenceexception was unhandled”在较早的物理引擎body.cs中

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

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

+0

我们可以有完整的堆栈跟踪吗? – user7116

+0

请参阅:http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net –

+1

你还没有发布你说错误的代码行。无论如何,在该行放置一个断点并调试您的代码。当它到达断点时,将鼠标悬停在对象上并查看哪一个为空。当你试图访问一个null对象的成员时,你会得到这个异常。找到null并修复它。 –

回答

0

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