Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <iostream>
#include <iomanip>
#include <Box2D/Box2D.h>
using namespace std;
int main()
{
//Construct a b2World
b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);
//Request b2World's body factory to construct a b2Body
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0.0f, -10.0f);
b2Body* groundBody = world.CreateBody(&groundBodyDef);
//Request b2Body's fixture factory to construct a fixture (a b2PolygonShape in this case)
b2PolygonShape groundBox;
groundBox.SetAsBox(50.0f, 10.0f);
groundBody->CreateFixture(&groundBox, 0.0f);
//Request b2World's body factory to construct a dynamic b2Body
b2BodyDef dynamicBodyDef;
dynamicBodyDef.position.Set(0.0f, 4.0f);
dynamicBodyDef.type = b2_dynamicBody;
b2Body* dynamicBody = world.CreateBody(&dynamicBodyDef);
//Request b2Body's fixture factory to construct a fixture (a b2PolygonShape in this case)
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(1.0f, 1.0f);
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
dynamicBody->CreateFixture(&fixtureDef);
// Prepare for simulation. Typically we use a time step of 1/60 of a
// second (60Hz) and 10 iterations. This provides a high quality simulation
// in most game scenarios.
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
// This is our little game loop.
for (int32 i = 0; i < 60; ++i)
{
// Instruct the world to perform a single step of simulation.
// It is generally best to keep the time step and iterations fixed.
world.Step(timeStep, velocityIterations, positionIterations);
// Now print the position and angle of the body.
b2Vec2 position = dynamicBody->GetPosition();
float32 angle = dynamicBody->GetAngle();
cout.width(7);
cout.precision(2);
cout.setf(ios::fixed);
cout << position.x << " "
<< position.y << " "
<< angle << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment