[Libgdx][Box2D] Box2D not scaling correctly [Fixed]

In my game, I use Box2D. Now Box2D doesn’t use pixels as units, so instead, it uses meters.

I render two things in my game to keep the physics and the graphics separate. Graphics is in normal libgdx coordinates (lower-left origin) because I’m used to having it as that. Physics is in Box2D coordinates (center origin) because that’s what Box2D needs.

Everything seems fine, except that Box2D renders everything twice as big:

White line is the graphics renderer while the green lines are from the Box2D debug renderer

(Yeah I know it’s not centered but it’s on purpose)


//I set 60 pixels per meter
private static final int PIXELS_PER_METER = 60;

private Box2DDebugRenderer debug;
private OrthographicCamera camera;

//...

public ...() {
	debug = new Box2DDebugRenderer();
	//Convert window width and height to meters because that's what Box2D needs
	camera = new OrthographicCamera(Maths.pixelsToMeters(Gdx.graphics.getWidth()), Maths.pixelsToMeters(Gdx.graphics.getHeight()));

	//Just offset the camera, because in-game center isn't the window center; not sure if this is relevant
	camera.position.sub(0f, Maths.pixelsToMeters(Gdx.graphics.getHeight() - Maths.IN_GAME_HEIGHT / 2f - Gdx.graphics.getHeight() / 2f), 0f);
	
	camera.update();
}

//...

public static float pixelsToMeters(float p) {
	return p / (float)(PIXELS_PER_METER);
}

//...

public void render(float delta, SpriteBatch batch) {
	camera.update();
	//...
	debug.render(world, camera.combined);
}

Given that the cube above is 60 by 60 pixels, that would be 1 meter in Box2D units (println’s also say this). But every time it is rendered it shows up twice as big (120 by 120 pixels). It also said in the javadocs that OrthographicCamera takes in half a viewport, but that still doesn’t work.

I personally don’t use box2d but the libgdx doc says that PolygonShape.setAsBox() takes in half-size arguments. Could it be that you’re setting the box to be 1x1, but the parameters assume that’s half size and make it 2x2? Your body definition code isn’t included so we can’t tell.

Well I’ll be, it seems you’re right


bodyDef = new BodyDef();
bodyDef.angle = this.rotation;
bodyDef.position.set(this.x, this.y);
bodyDef.type = BodyDef.BodyType.StaticBody;
body = w.createBody(bodyDef);
poly = new PolygonShape();
poly.setAsBox(this.width, this.height); //should have been halved
fix = new FixtureDef();
fix.friction = this.friction;
fix.restitution = this.resituition;
fix.shape = poly;
body.createFixture(fix);

I guess I should have read the docs more :clue: I have this bad habit of just quickly scanning over wikis and just picking what I think I need

It’s fixed now, thanks!