I am working about box2D.

Even if I set userData, when I retrieve it via getUserData(), it returns null. Using debugger, I noticed that object passed to setUserData() is not null, but on the next istruction: fixtureDef.shape.dispose();

Body user data returns being null, such as setUserData() set on a copy of body. I read on other topics that setUserData() must be called before body creation...but it throws an exception

public void setPhysic(@Null Shape shape, BodyDef.BodyType bodyType, FixtureDef fixtureDef) {

    if(shape == null) {
        PolygonShape polygonShape = new PolygonShape();
        BoundingBox boundingBox = this.model.calculateBoundingBox(new BoundingBox());
        polygonShape.setAsBox(boundingBox.getWidth(), boundingBox.getHeight());
        fixtureDef.shape = polygonShape;
        fixtureDef.density = 1f;
        fixtureDef.shape = shape;

    BodyDef bodyDef = new BodyDef();
    bodyDef.type = bodyType;
    bodyDef.position.set(this.getPosition().x, this.getPosition().y);

    this.body = Game.world.createBody(bodyDef);
    this.body.setUserData(this); //<-- Add this line to fix the problem


Here I get userData:

  if(body[0].getUserData() instanceof Block){
            if(button == Input.Buttons.RIGHT){
            }else if(button == Input.Buttons.LEFT){
                player.onPlayerBlockDestroying((Block)body[0].getUserData(), mouseCords);
  • \$\begingroup\$ Fixed! I read doc again: in order to set user data to body, I had to call Body#setUserData(), which is different by Fixture#getUserData(). Now I call both. I am also gonna edit code above in order to help who has my same problem \$\endgroup\$
    – DynoZ
    Apr 7 '21 at 10:02

You must log in to answer this question.

Browse other questions tagged .