问题
I am using java, libgdx, and box2d
In main class I have created a player. I want to change shape.setAsBox to 100 in player class. So in other words I want to change shape.setAsBox after it has been created. I believe only way to do this is to delete fixture and recreate a new one with 100 size. How can I do this.
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);
...
}
}
// playyer class
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.
}
}
回答1:
The best (probably the only) way to do it is to actually destroy the entire Fixture and redefine it. Since your player only has one Fixture, either you keep track of it to remove it or you just do this:
this.getBody().destroyFixture(this.getBody().getFixtureList().first());
Then just recreate a simple shape in the already existing 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();
来源:https://stackoverflow.com/questions/24967337/how-to-change-size-after-it-has-been-created