Skip to content Skip to sidebar Skip to footer

How To Handle Null Pointer Exception In Libgdx's Box2d Contactlistener?

What's up everyone, I am heuristically producing a Pong clone in Box2D via libGDX. The Null Pointer Exception is originating in the ContactListener's beginContact() method in which

Solution 1:

Set the userdata for each body in the Box2D world so that you can use conditional logic within the ContactListener to assess whether or not the collision should be handled.

With the emphasis being on the line paddleBody.setUserData(4); below. You can pick any number to set to the userdata of the individual object, so long as the number is unique from the userdata of the other objects within your world.

For example:

/**paddle1**/BodyDefpaddleDef=newBodyDef();
    paddleDef.type = BodyType.DynamicBody;
    paddleDef.position.set(width * 0.2f, height / 2);
    paddleDef.fixedRotation = true;

    BodypaddleBody= world.createBody(paddleDef);
    paddleBody.setUserData(4);

    PolygonShapepaddleShape=newPolygonShape();
    paddleShape.setAsBox(3.0f, 15.0f); //half-width and half-heightFixtureDefpaddleFD=newFixtureDef();
    paddleFD.shape = paddleShape;
    paddleFD.density = 10.0f;
    paddleFD.friction = 0.0f;
    paddleFD.restitution = 0.1f;

    paddleBody.createFixture(paddleFD);

    paddleShape.dispose();

    paddleBody.setLinearVelocity(0.0f, 0.0f);
    /**end paddle1**//**paddle2**/BodyDefpaddleDef2=newBodyDef();
    paddleDef2.type = BodyType.DynamicBody;
    paddleDef2.position.set(width * 0.8f, height / 2);
    paddleDef2.fixedRotation = true;        

    BodypaddleBody2= world.createBody(paddleDef2);
    paddleBody2.setUserData(5);             

    PolygonShapepaddleShape2=newPolygonShape();
    paddleShape2.setAsBox(3.0f, 15.0f); //half-width and half-heightFixtureDefpaddleFD2=newFixtureDef();
    paddleFD2.shape = paddleShape2;
    paddleFD2.density = 10.0f;
    paddleFD2.friction = 0.0f;
    paddleFD2.restitution = 0.1f;

    paddleBody2.createFixture(paddleFD2);

    paddleShape2.dispose();

    paddleBody2.setLinearVelocity(0.0f, 0.0f); // Move nowhere at a rate of x = 0.0f, y = 0.0f meters per second/**end paddle2**/

Post a Comment for "How To Handle Null Pointer Exception In Libgdx's Box2d Contactlistener?"