Body body = world.createBody(bodyDef) throws a NullPointerEx

Hi guys,

Here's my code (java) that makes a ball and adds it to the world.

Code:
    public void makeBall(float x, float y, float radius, float density, int color) {
       
       CircleDef def = new CircleDef();
       def.density = density;
       def.friction = 0.2f;
       def.radius = radius/pixRate/2;
       def.restitution = 0.4f;
       
       BodyDef bodyDef = new BodyDef();
       bodyDef.position.set(x/pixRate, y/pixRate);
       Body body = world.createBody(bodyDef);  // <- about 20% of the time, the body is null
       
       int i = 0;
       while ( body ==  null )
       {
          body = world.createBody(bodyDef); // <- usually it will become not null after 40000 - 70000 attempts.
          i++;
       }
       
       Log.e("BALL: ", "null was thrown "+String.valueOf(i)+" times." );
       
       body.createShape(def);
       body.setMassFromShapes();
       
       BodyWithPoly bwp = new BodyWithPoly();
       bwp.body = body;
       bwp.cDef = def;
       bwp.color = color;
       BodyPolyArray.add(bwp);
   
    }


Most of the times it works fine, yet sometimes the body is null and it takes about 40000 - 70000 attempts to recover.

What do you think might be causing it? Maybe the world doesn't want to accept a new body at some conditions? Is there a better way to fix that?


Thanks! 🙂
Check this post:

viewtopic.php?f=8&t=4657

I think it has something to do with where you are calling the function makeBall, or createBody to be specific.

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