#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
#include <iostream>
#define PPM 30 // Pixel Per Meters
using namespace sf;
b2World *myWorld;
b2Body *boxBody;
b2Body *lineBody;
void updatePhysics()
{
float32 timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
myWorld->Step(timeStep, velocityIterations, positionIterations);
}
void initPhysics()
{
// set up the world
b2Vec2 gravity(0.0f,9.8f);
myWorld = new b2World(gravity,true);
// box body definition
b2BodyDef boxBodyDef;
b2Vec2 boxVelocity;
boxVelocity.Set(0.0f,10.0f);
boxBodyDef.type = b2_dynamicBody;
boxBodyDef.position.Set(550.0f/PPM,45.0f/PPM);
boxBodyDef.linearVelocity = boxVelocity;
// line body definition
b2BodyDef lineBodyDef;
lineBodyDef.type = b2_staticBody;
lineBodyDef.position.Set(400.0f/PPM,375.0f/PPM);
// create the bodies
boxBody = myWorld->CreateBody(&boxBodyDef);
lineBody = myWorld->CreateBody(&lineBodyDef);
// create the shapes
b2PolygonShape boxShape,lineShape;
boxShape.SetAsBox(50.0f/PPM,25.0f/PPM);
lineShape.SetAsEdge(b2Vec2(50.0f/PPM,550.0f/PPM),b2Vec2(750.0f/PPM,200.0f/PPM));
// add fixtures
b2FixtureDef boxFixtureDef,lineFixtureDef;
boxFixtureDef.shape = &boxShape;
lineFixtureDef.shape = &lineShape;
boxFixtureDef.density = 1;
boxBody->CreateFixture(&boxFixtureDef);
lineBody->CreateFixture(&lineFixtureDef);
}
int main()
{
bool running = true;
initPhysics();
RenderWindow app(VideoMode(800,600,32),"First Test",Style::Close);
Shape box = Shape::Rectangle(500,20,600,70,Color::White);
Shape ground = Shape::Line(50,550,750,200,1,Color::Red);
while(running)
{
Event event;
while(app.GetEvent(event))
{
if(event.Type == Event::Closed)
running = false;
}
updatePhysics();
b2Vec2 pos = boxBody->GetPosition();
box.SetPosition(pos.x*PPM,pos.y*PPM);
app.Clear();
app.Draw(box);
app.Draw(ground);
app.Display();
}
app.Close();
delete myWorld;
return EXIT_SUCCESS;
}