"nullreferenceexception was unhandled" body.cs

Oct 5, 2011 at 7:24 PM

I'm a c++ programmer trying out c#. I've done a lot with box2d in c++, but this is my first time with c#. So, I'm trying to make a simple game with farseer. When I try to compile my code, it stops in body.cs at:

IBroadPhase broadPhase = World.ContactManager.BroadPhase;

With the error in the title. I believe the problem is in my Player class, so here's the code for that:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Controllers;


namespace MMM
{
    /// 
    /// This is a game component that implements IUpdateable.
    /// 
    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);
        }

        public override void LoadContent()
        {
            base.LoadContent();
        }

        public override void UnloadContent()
        {
            base.UnloadContent();
        }
        /// 
        /// 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);
        }
    }
}

The testbed runs fine, so I'm pretty sure my code is the problem, and not farseer. Thanks in advance.

Oct 6, 2011 at 11:06 PM

Try using body=BodyFactory.CreateRectangle(World, 2,2,1); in the initializer. My guess is that the body doesn't have an associated fixture (that the other Create functions use).

If that doesn't work, show us where you initialize the Player. I would recommend Initializing inside the constructor.

Oct 7, 2011 at 3:53 AM

Same error. Tried initializing in the Game1() Constructor. Same error. Heres the Game1.cs file. Player is initialized in the Initialize() function.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using FarseerPhysics;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using FarseerPhysics.Collision;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Controllers;

namespace MMM
{
    /// 
    /// This is the main type for your game
    /// 
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        /*Vector2 playerPosition;*/
        SpriteBatch playerSprite;
        Texture2D playerTexture;
        Player player;
        World world;
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// 
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// 
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            playerSprite = new SpriteBatch(GraphicsDevice);
            playerTexture = this.Content.Load("player");
            base.Initialize();
            player = new Player();
            player.Initialize(world, playerSprite, playerTexture);
        }

        /// 
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// 
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.

            // TODO: use this.Content to load your game content here
        }

        /// 
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// 
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// 
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// 
        /// <param name="gameTime" />Provides a snapshot of timing values.
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// 
        /// This is called when the game should draw itself.
        /// 
        /// <param name="gameTime" />Provides a snapshot of timing values.
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            player.Draw(gameTime);
            // TODO: Add your drawing code here
            //player.Draw(gameTime);
            base.Draw(gameTime);
        }
    }
}
Thanks again. :)

Oct 7, 2011 at 7:33 PM
Edited Oct 7, 2011 at 7:39 PM

Hey,

1)

http://blog.nickgravelyn.com/images/xna-game-flow.jpg9

Initialization is technically for things that occur once, and before anything else is supposed to happen. ie. game constants (Gravity=Vector2.Zero, SpritePath="Content\MySprites\")

It initializes the game

 

LoadContent is a little more specific. For levels, it means creating obstacles in different places.

 

When you're first starting out, I recommend stuffing everything in LoadContent. Use Initialization when

 

2)

Game1.world is never constructed. This is probably the cause of the nullreference exception.

I imagine that when you run "body = BodyFactory.CreateBody(world);", to the program it looks like "body = BodyFactory.CreateBody(null);"


Put world=new World(Vector2.Zero); somewhere before player initialization

 

3)

Even if it runs, you won't see any physics.

You'll need

world.Step(1) in the update

 

4)

I do not recommend calling "Spritebatch.Begin()" in Player.Draw().

This implies that you will run "Spritebatch.Begin()" for every body

I don't remember how much of a difference it will make, but it's something to keep in mind if your game starts to stutter.

 

I hope this works out!

Oct 8, 2011 at 10:55 AM

fnorder is right. just some small supplements:

world.Step((float)gameTime.ElapsedGameTime.TotalSeconds);

also try to make the texture for the player and others static to save memory.

Oct 11, 2011 at 11:13 PM

Thanks guys! Now I just have one more problem, but I started a new thread for that. :)