This project is read-only.

Adding a PhysicsSpite in code behind..

Nov 5, 2012 at 3:16 AM

I have tried to add a physics sprite in code behind, but am running into several null reference exceptions. Am I missing something here?

 here is a snapshot of the code I am trying

PhysicsSprite wallLeft = new PhysicsSprite();
wallLeft.Name = "wallLeft";
wallLeft.Width = 1;
wallLeft.Height = relativeHeight;
Canvas.SetTop(wallLeft, 0);
Canvas.SetLeft(wallLeft, 0);
wallLeft.ShapeType = "Rectangle";
wallLeft.BodyObject = new FarseerPhysics.Dynamics.Body(cnvGame.Simulator);
cnvGame.AddPhysicsSprite(wallLeft, true);


Nov 5, 2012 at 2:07 PM

I'm not sure why you're setting the BodyObject in this line?

wallLeft.BodyObject = new FarseerPhysics.Dynamics.Body(cnvGame.Simulator);

The bodyobject is set by the physics helper for you when the control is loaded into the canvas so you shouldn't need this.

Also, what is relativeHeight? (and width is pretty skinny, unless you are using Bullets everywhere things could pass through it).

But that's just a couple of things I noticed, not sure what is going on. If you still have problems, can you post the line of code that is raising the null reference exception, and the exception details?


Dec 19, 2012 at 8:52 PM
Edited Dec 19, 2012 at 8:54 PM

Great tip. I found that the BodyObject was empty after adding a sprite in code behind. This post gave me an hint to look into the issue.

FYI: The BodyObject is set in PhysicsSprite.cs in the function PhysicsSprite_Loaded.

I first added some sprites in code behind, and tried to access the bodyobject so I could store it in a list. I found out that you have to wait until the Xaml Sprite is loaded. After that the bodyobject is set. After that you can access the body.

So now am I still puzzling on how to set the initial rotation of a created sprite. And when to add joints using the World object on the just created sprites since I can't do that immediately after I added the sprite since there is no bodyobject available then.