0
\$\begingroup\$

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

      @Override
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;
    }else{
        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
    this.body.createFixture(fixtureDef).setUserData(this);

    fixtureDef.shape.dispose();
}

Here I get userData:

  if(body[0].getUserData() instanceof Block){
            if(button == Input.Buttons.RIGHT){
                ((Block)body[0].getUserData()).onBlockClicked(player);
            }else if(button == Input.Buttons.LEFT){
                player.onPlayerBlockDestroying((Block)body[0].getUserData(), mouseCords);
            }
        }
\$\endgroup\$
1
  • \$\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 .