5
« on: May 27, 2010, 10:52:47 am »
It seems that all the threads I could find on this were code-less and were eventually solved without explaining HOW they were solved. I'm attempting to get Box2D and SFML to play nicely together, and they do seem to for the most part, but I'm having a TINY issue in getting everything to line up as they should. My box object likes to hover about 9 pixels above my ground object and I can't seem to figure out why.
#include <SFML/Graphics.hpp>
// Box2D Header
#include <Box2D/Box2D.h>
int main() {
// Create the SFML Window
sf::RenderWindow Game(sf::VideoMode(800, 600, 32), "SFML Blank Window");
Game.SetFramerateLimit(60);
//Create the SFML Event handler
sf::Event Event;
// Create the SFLM shape
sf::Shape box = sf::Shape::Rectangle(0, 0, 50, 50, sf::Color(127, 0, 0, 255));
//box.SetCenter(25, 25);
sf::Shape ground = sf::Shape::Rectangle(0, 0, 800, 10, sf::Color(0, 127, 0, 255));
//box.SetCenter(400, 5);
// Set the box position
box.SetPosition(100, 100);
ground.SetPosition(0, 580);
// Create the image buffer
sf::Image image;
if (!image.LoadFromFile("box.jpg"))
return EXIT_FAILURE;
// Create the SFML sprite
sf::Sprite sprite;
// Set the sprites image
sprite.SetImage(image);
// Set up world properties
bool doSleep = true;
b2Vec2 gravity(0, 10.0f);
int iterations = 10;
float scale = 30;
float timeStep = 1.0f / 60.0f;
// Create the world
b2World world(gravity, doSleep);
// Set up box properties
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(100/scale, 100/scale);
b2Body* body = world.CreateBody(&bodyDef);
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(50/scale, 50/scale);
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicBox;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.3f;
body->CreateFixture(&fixtureDef);
//body->SetTransform(body->GetPosition(), 10);
// Create ground
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0/scale, 580/scale);
b2Body* groundBody = world.CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
groundBox.SetAsBox(800/scale, 10/scale);
b2FixtureDef groundFixDef;
groundFixDef.shape = &groundBox;
groundFixDef.restitution = 0.5f;
groundBody->CreateFixture(&groundFixDef);
while (Game.IsOpened()) {
while (Game.GetEvent(Event)) {
if (Event.Type == sf::Event::Closed)
Game.Close();
}
world.Step(timeStep, 10, 1);
world.ClearForces();
b2Vec2 pos = body->GetPosition();
float32 angle = body->GetAngle();
box.SetPosition(pos.x*scale, pos.y*scale);
box.SetRotation(-(angle*(180/b2_pi)));
Game.Clear();
Game.Draw(sprite);
Game.Draw(box);
Game.Draw(ground);
Game.Display();
}
return EXIT_SUCCESS;
}
Any help would be appreciated. Thank you!