2011-10-06 69 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);來修復它。