I am creating a platformer, and I’m having some trouble understanding/setting Box2D correctly. Right now my issue is that the player, which is constructed using a dynamic body, is stopping in mid-air right above my platforms, which are static bodies. He doesn’t hit the platform. A screenshot of what I mean:
As you can see, the player is floating on top of the platform. If you look closely, you can see a little dot where the corner of the hitbox is colliding with the platform, but no matter what I try I cannot get the player to actually hit the platform. I’ll show my code now.
This is how I create the player:
public static Body getDynamicBody(World world, float x, float y, float width, float height) {
BodyDef def = new BodyDef();
def.type = BodyType.DynamicBody;
def.position.set(x * Game.WORLD_TO_BOX, y * Game.WORLD_TO_BOX);
Body body = world.createBody(def);
body.setFixedRotation(true);
PolygonShape shape = new PolygonShape();
shape.setAsBox((width / 2) * Game.WORLD_TO_BOX, (height / 2) * Game.WORLD_TO_BOX);
FixtureDef fixture = new FixtureDef();
fixture.shape = shape;
fixture.density = 1;
body.createFixture(fixture);
shape.dispose();
return body;
}
And then rendering the player:
@Override
public void render(SpriteBatch batch) {
Sprite sprite = (Sprite) body.getUserData();
sprite.setSize(width, height);
float width = (sprite.getWidth() / 2) * Game.WORLD_TO_BOX;
float height = (sprite.getHeight() / 2) * Game.WORLD_TO_BOX;
sprite.setPosition((body.getPosition().x - width) * Game.BOX_TO_WORLD, (body.getPosition().y - height) * Game.BOX_TO_WORLD);
sprite.draw(batch);
}
Here is how I create the platform:
public static Body getStaticBody(World world, float x, float y, float width, float height) {
BodyDef def = new BodyDef();
def.position.set(x * Game.WORLD_TO_BOX, y * Game.WORLD_TO_BOX);
Body body = world.createBody(def);
PolygonShape shape = new PolygonShape();
shape.setAsBox((width / 2) * Game.WORLD_TO_BOX, (height / 2) * Game.WORLD_TO_BOX);
body.createFixture(shape, 0.0f);
FixtureDef fixture = new FixtureDef();
fixture.shape = shape;
body.createFixture(fixture);
shape.dispose();
return body;
}
And rendering is the same as the player. I update the Box2D like this:
world.step(1.0f / 60f, 5, 8);
And rendering it:
debugRenderer.render(world, getMain().getDebugCamera().combined.cpy().scale(Game.BOX_TO_WORLD, Game.BOX_TO_WORLD, 1));
Why would my player be floating above the platform?