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);
_body->initWorld(position);
_sprite = createComponent<pin::Sprite>(this);
_sprite->initRender(dimensions, pin::TextureManager::loadTexture("crate.png"), _body);
//PHYSICS STUFF
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(position.x, position.y);
_physics = world->CreateBody(&bodyDef);
//Fixture&Shape
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:
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?