i'm using SDL2.0/OpenGL + Box2D with C++ to learn some stuff about games, so i created two rectangles bodies: a small box(dynamic) wich will fall into the second body: the ground(static), i draw them on the screen with OpenGL primitives, as recomended i'm not using "pixel thinking", i'm using meters to represent everything, well, the problem is that i can't get a good physic simulation, just almost, when rendering i can see the small box falling into the ground but it don't touch the ground, it gets real close but don't touch, i really can't understand why, so i came here to see if can get some help:
Here we create the bodies(and do other things):
void MyLoop::onCreate(){
world = new b2World(b2Vec2(0, -10));
player = new Player(world);
//creates the player body
player->create();
//Creates the ground
b2BodyDef bdef;
b2PolygonShape* pshape = new b2PolygonShape();
b2FixtureDef fdef;
bdef.type = b2_staticBody;
ground = world->CreateBody(&bdef);
pshape->SetAsBox(40.0f, 1.0f);
fdef.shape = pshape;
ground->CreateFixture(&fdef);
ground->SetTransform(b2Vec2(20.0f, 0.5f), 0);
glMatrixMode(GL_MATRIX_MODE);
glLoadIdentity();
//configurating the apropriate scale
glOrtho(0, 40, 0, 20, 1, -1);
delete pshape;
}
The most important here is the bodies creation and the glOrtho call wich will set the camera to our coordinate system.
The creation of the player body:
b2BodyDef bdef;
bdef.type = b2_dynamicBody;
pbody = world->CreateBody(&bdef);
b2PolygonShape* pshape = new b2PolygonShape();
pshape->SetAsBox(0.5f, 1.0f);
b2FixtureDef fdef;
fdef.shape = pshape;
pbody->CreateFixture(&fdef);
pbody->SetTransform(b2Vec2(19.0f, 10.0f), 0);
So now we go to the render loop: i get the bodies position with getPosition() method and use them to draw the bodies:
glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
player->render();
float x = ground->GetPosition().x;
float y = ground->GetPosition().y;
renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 0.0f, 1.0f);
renderer.drawRectangle(x - 20.0f, y + 0.5f, 40.0f, 1.0f);
renderer.end();
SDL_GL_SwapWindow(window);
world->Step(1 / 20.0f, 8, 3);
The player render:
float x = pbody->GetPosition().x;
float y = pbody->GetPosition().y;
renderer.begin(GL_QUADS);
renderer.setColor(0.0f, 1.0f, 0.0f);
renderer.drawRectangle(x - 0.25f, y + 0.5f, 0.5f, 1.0f);
renderer.end();