I'm trying to code some breakout games with LibGDX and Box2D. But there is one point that I don't understand. There are must be two bricks only touch with edge. But on emulator I just saw two bricks nested.
Here's createBox method's code:
private void createBox(float posX, float posY, float boxW, float boxH) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(posX, posY);
Body body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(boxW, boxH);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;
Fixture fixture = body.createFixture(fixtureDef);
shape.dispose();
}
edit: That multiplied code.
createBox(CONS_HOLDER.BRICKS_LEFT_MARGIN + (i * CONS_HOLDER.BRICK_WIDTH * 2 ),
CONS_HOLDER.BRICK_TOP_SCREEN_MARGIN + (j * CONS_HOLDER.BRICK_HEIGHT * 2 ) + CONS_HOLDER.BRICKS_TOP_MARGIN,
CONS_HOLDER.BRICK_WIDTH / 2,
CONS_HOLDER.BRICK_HEIGHT / 2);
The documentation for setAsBox(float, float)
states that the parameters are half-width
and half-height
. You should divide the dimensions of your boxes in half in order to get the correct size.
private void createBox(float posX, float posY, float boxW, float boxH) {
BodyDef bodyDef = new BodyDef();
bodyDef.type = BodyDef.BodyType.StaticBody;
bodyDef.position.set(posX, posY);
Body body = world.createBody(bodyDef);
PolygonShape shape = new PolygonShape();
shape.setAsBox(boxW / 2.f, boxH / 2.f);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = shape;
fixtureDef.density = 1f;
Fixture fixture = body.createFixture(fixtureDef);
shape.dispose();
}
Documentation: https://libgdx.badlogicgames.com/nightlies/docs/api/com/badlogic/gdx/physics/box2d/PolygonShape.html#setAsBox-float-float-