【发布时间】:2011-10-08 20:41:52
【问题描述】:
我是一名尝试 c# 的 c++ 程序员。我在 c++ 中使用 box2d 做了很多工作,但这是我第一次使用 c#。所以,我正在尝试用 farseer 物理引擎制作一个简单的游戏。当我尝试编译我的代码时(我使用的是 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 测试平台运行良好,所以我很确定我的代码是问题所在,而不是 farseer。如果您需要查看我的更多代码,请告诉我。我也在farseer论坛上发布了这个,所以如果我在那里得到答案,我会告诉你们。提前致谢。
【问题讨论】:
-
我们可以有完整的堆栈跟踪吗?
-
您还没有发布您说错误的代码行。无论如何,在该行放置一个断点并调试您的代码。当它到达断点时,将鼠标悬停在对象上并查看哪个为空。当您尝试访问为 null 的对象的成员时,您将收到此异常。找到空值并修复它。