Applying force in a custom class?

Oct 5, 2007 at 9:52 AM
I've created a ball class for a game I'm working on. I want to be able to apply force to the ball inside that class, but I keep getting run-time errors due to the physics object not being a reference. It's a bit tricky to display, so here's a example.

public void update(GameTime gt)
{

ballBody.ApplyForce(new Vector2(-400, 0));
physicsSimulator.Update(gt.ElapsedGameTime.Milliseconds * .001f);

}

Running that code, when it attempts to update I get an error saying:
NullReferenceException was unhandled.
Object reference not set to an instance of an object.

If I put in error handling the code just never gets executed.
Coordinator
Oct 5, 2007 at 11:20 AM
Is the ballBody a member of this class? I'd need to see more code to know what is going. What you describe doing should not be an issue.

Did you new-up the physics simulator? physicSimulator = new PhysicsSimulator(gravity) ?
Oct 5, 2007 at 1:18 PM
It looks like either ballBody or physicsSimulator is null. When you get the exception, hover over these two variables and see which one is null, and make sure it's being created properly and being created before this code executes.
Oct 5, 2007 at 1:28 PM
Here's the entire class:


//display variables
Texture2D ballTex;

//physics variables
PhysicsSimulator physicsSimulator;

Body ballBody;
Geometry ballGeom;

public void Tennis2()
{
physicsSimulator = new PhysicsSimulator(new Vector2(0, 1));

ballBody = BodyFactory.Instance.CreateCircleBody(physicsSimulator, 12, 5);
ballBody.Position = new Vector2(200, 200);

ballGeom = GeometryFactory.Instance.CreateCircleGeometry(physicsSimulator, ballBody, 12, 12);
}

public void load(ContentManager aLoader)
{
ballTex = aLoader.Load<Texture2D>("ball") as Texture2D;
}

public void draw(SpriteBatch mSpriteBatch)
{
mSpriteBatch.Draw(ballTex, new Rectangle(200, 200, 14, 14), new Rectangle(0, 0, 20, 20), Color.White);
}

public void update(GameTime gt)
{

ballBody.ApplyForce(new Vector2(-400, 0));
physicsSimulator.Update(gt.ElapsedGameTime.Milliseconds * .001f);

}



It says both of the lines in update() are null.
Coordinator
Oct 5, 2007 at 4:34 PM
Edited Oct 5, 2007 at 4:35 PM
Change 'public void Tennis2()' to 'public Tennis2()'

It is a constructor and does not require the void return type to be declared.

That code was never being run.
Oct 5, 2007 at 4:43 PM
I can't believe I missed that. It should actually be Ball(), as it's the Ball class, it wasn't compiling without a return type with the Tennis2 name, so I just there in void to shut it up.