创建后如何更改大小

use*_*249 1 box2d libgdx

我正在使用 java、libgdx 和 box2d

在主类中我创建了一个播放器。我想在玩家类中将 shape.setAsBox 更改为 100 。换句话说,我想在创建 shape.setAsBox 后对其进行更改。我相信做到这一点的唯一方法是删除夹具并重新创建一个大小为 100 的新夹具。我怎样才能做到这一点。

public class main{
  ...
  public main(){
    //create player
    BodyDef bdef = new BodyDef();
    Body body;
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();

    /***Body - Player ***/
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(50 / PPM, 50 / PPM);
    bdef.linearVelocity.set(1.5f, 0);
    body = world.createBody(bdef);

    /*** 1st fixture ***/
    shape.setAsBox(50/ PPM, 50 / PPM);
    fdef.shape = shape;
    fdef.filter.categoryBits = Constants.BIT_PLAYER;
    fdef.filter.maskBits = Constants.BIT_GROUND;
    body.createFixture(fdef).setUserData("player");

    player = new Player(body);
  }

  ....

  public void update(float dt) {
      playerObj.update(dt);
      ...
  }
}
Run Code Online (Sandbox Code Playgroud)

// 玩家类

 public class player{
       public player(Body body){
             super(body);
       }

       ....
       public void update(){
             //get player x position
             currentX = this.getBody().getPosition().x;

             // how can I delete old fixture and recreate a new one? 
             // which will has shape.setAsBox = 100.
       }
}
Run Code Online (Sandbox Code Playgroud)

Xky*_*nar 5

摧毁Fixture并重新定义它。由于您的播放器有一个Fixture,请跟踪它以将其删除或调用:

this.getBody().destroyFixture(this.getBody().getFixtureList().first());
Run Code Online (Sandbox Code Playgroud)

然后在已经存在的 Body 中重新创建一个简单的形状:

PolygonShape shape;
FixtureDef fdef;

// Create box shape
shape = new PolygonShape();
shape.setAsBox(100 / PPM, 100 / PPM);

// Create FixtureDef for player collision box
fdef = new FixtureDef();
fdef.shape = shape;
fdef.filter.categoryBits = Constants.BIT_PLAYER;
fdef.filter.maskBits = Constants.BIT_GROUND;

// Create player collision box fixture
this.getBody().createFixture(fdef).setUserData("player");
shape.dispose();
Run Code Online (Sandbox Code Playgroud)