I've decided to try to use the Box2D physics engine in my game, and as I started I'm facing weird behaviour. I've followed a video tutorial where we setup the Box2D world with world gravity, and then create an entity containing the collider.

Here's how I'm creating the entities:

void PhysicsEntity::init(b2World* world, vec2 position, vec2 dimensions)
    _body = createComponent<pin::WorldComponent>(this);

    _sprite = createComponent<pin::Sprite>(this);
    _sprite->initRender(dimensions, pin::TextureManager::loadTexture("crate.png"), _body);

    b2BodyDef bodyDef;
    bodyDef.type = b2_staticBody;
    bodyDef.position.Set(position.x, position.y);

    _physics = world->CreateBody(&bodyDef);

    b2PolygonShape boxShape;
    boxShape.SetAsBox((dimensions.x) / 2.0f, (dimensions.y) / 2.0f);

    b2FixtureDef fixDef;
    fixDef.shape = &boxShape;
    fixDef.density = 10.0f;
    fixDef.friction = 0.3f;
    fixture = _physics->CreateFixture(&fixDef);

Here's the render function:

void PhysicsEntity::render(pin::SpriteBatch* batch)

    mat4 modelMatrix;
    vec3 position(_physics->GetPosition().x, _physics->GetPosition().y, 0.0f);

    modelMatrix = glm::translate(modelMatrix,position);
    modelMatrix = glm::rotate(modelMatrix, glm::radians(_physics->GetAngle()), vec3(0.0f, 0.0f, 1.0f));

    _sprite->render(batch, modelMatrix);

It looks like this with Box2D debug rendering turned on:

enter image description here

Here's a video of how it behaves.

It looks like the collider and sprites locations differ. I've read that I shouldn't use 1 pixel = 1 meter ratio, but in many tutorials it was working without problem so I'm wondering if I forgot something.

The step settings I'm using are:

_physicsWorld->Step(1.0f / 60.0f, 6, 2);

What have I missed?


1 Answer 1


The position of a Box2D body (from GetPosition) is its center, but your sprite rendering assumes the position is the bottom-left corner.

To correct this, render sprites with offsets of { x: width / 2, y: height / 2}.

  • \$\begingroup\$ Dude, you just saved me from a lot of headaches, thanks a lot! How did I miss that fact it returns the center instead of the bottom-left.. \$\endgroup\$
    – Pins
    Jan 10, 2018 at 23:37
  • \$\begingroup\$ Happy to help. :) I remember I had the same problem when I was starting to learn Box2D. Good luck! \$\endgroup\$
    – Anko
    Jan 10, 2018 at 23:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .