FixtureDef null pointer exception?

Hey! I'm working on my assignment (top down shooter/action game) and occasionally I get a null pointer exception on this line when I create a new body:

Code:
body.createFixture( fixtureDef );


The bug can be replicated by shooting. Some of the projectiles will throw the error despite the fact that they are all created the same way.

Here's the code for BaseProp from which all entities are based upon. Any ideas? 😢

Code:
public class BaseProp
{
    public BufferedImage image;                                     
    public DoubleObject rotation = new DoubleObject(0);
    public IntObject instanceID = new IntObject(0);                 
    public IntObject typeID = new IntObject(0);                     
    public CollisionUserData userData;                             
   
    public Body body;
    public BodyDef bodyDef;
    public FixtureDef fixtureDef;
   
    public BaseProp( World world, String setImage, int setInstanceID, int setTypeID, float setX, float setY, BodyType setBodyType, float setLinearDamping, float setAngularDamping, float setDensity, boolean isBox )
    {
        loadImage( setImage );
       
        //Body
        bodyDef = new BodyDef();
        bodyDef.type = setBodyType;
        bodyDef.linearDamping = setLinearDamping;
        bodyDef.angularDamping = setAngularDamping;
        bodyDef.position = new Vec2( setX, setY);
        body = world.createBody( bodyDef );
       
        //Box Shape
        if( isBox )
        {
            PolygonShape shape = new PolygonShape();
            shape.setAsBox( ( image.getWidth() / Config.PHYS_RATIO ) * 0.5f, ( image.getHeight() / Config.PHYS_RATIO ) * 0.5f);
            fixtureDef = new FixtureDef();
            fixtureDef.density = 1f;
            fixtureDef.shape = shape;
            body.createFixture( fixtureDef );
        }
        //Circle Shape
        else
        {
            CircleShape shape = new CircleShape();
            shape.m_radius = ( image.getHeight() / Config.PHYS_RATIO ) * 0.5f;
            fixtureDef = new FixtureDef();
            fixtureDef.density = setDensity;
            fixtureDef.shape = shape;
            //TODO throws null pointer exception.
            body.createFixture( fixtureDef );
        }
       
        typeID.value = setTypeID;
        instanceID.value = setInstanceID;

        //Userdata
        userData = new CollisionUserData( instanceID, typeID );
        body.setUserData( userData );       
    }
   
    /*
     * Protected Methods
     */
   
    protected void loadImage( String imagePath )
    {
        try
        {
            image = ImageIO.read( new File( imagePath ) );
        }
        catch ( IOException e )
        {
            System.out.println( "Could not load image: " + imagePath );
        }
    }
   
    /*
     * Public Methods
     */
   
    public void setMassData( float mass )
    {
        //Mass Data
        MassData massData = new MassData();
        massData.mass = mass;
        body.setMassData( massData );
    }
   
    public void setBullet( boolean isBullet )
    {
        body.setBullet( isBullet );
    }
   
    public void setAngle( float angle )
    {
        getBody().setTransform( getBody().getPosition(), angle );
    }
   
    public Body getBody()
    {
        return body;
    }
}

This is most likely because you are trying to create a new Body when the World is currently being updated. In other words, during the execution of world.step(...). Doing this is not possible. You cannot modify the world in this way while the world is being updated. You will not get an error while trying to create a new Body, Fixture or Joint but instead null will be returned by any of the creation functions.

With that in mind you will need to synchronize the creation of new Body(s) with the updating of the world.

I imagine you are trying to create these new bodies within a separate thread? Perhaps triggered by mouse or key events?

A simple approach to synchronization would be like this:

Your encapsulating class should have an init() function which will create the body in the world. When you create a new object from another thread don't create the body at the same time. Instead add the encapsulating object to a queue for pending body creation then iterate over this queue before the next time you call the world.step(...) function. This will ensure that all bodies are created outside of the world.step(...) execution and avoid the not so good approach of surrounding the world.step(...) function with a synchronized(object){} block.

Putting words to better use and programming into practice. Something like this:

Encapsulating Object
Code:
public class EncObject
{
  // instance data
 
  public EncObject( ... )
  {
    // init object here
  }

  public void init( World world )
  {
    // create body instance according to instance data (i.e. world.createBody(...))
  }
}


In the Event thread.
Code:
// Create encapsulating object
EncObject encObject = new EncObject(...);

// Add object to pending new body queue
pendingWorldObjects.add( encObject );


In update thread (game loop)
Code:
// Create all pending new bodies.
while( ! pendingWorldObjects.isEmpty() )
{
  // Remove object from queue.
  EncObject encObject =  pendingWorldObjects.remove(0);

  // Create new body in world.
  encObject.init( world );
}

// Update world.
world.step(...);


Of course your encapsulating object can maintain a reference to the World Body and anything else you fancy. I have omitted all member variables since it is just the concept we are worried about and not a complete solution.

I will leave the rest to you 😀

Good luck and code hard my friend.
Thanks kostbot makes sense, the creation of bodies was based on a mouse click event. That solution is perfect! 🙂

Original thread: https://box2d.org/forum/viewtopic.php?t=7745