Hi! I am having a problem with positioning using Box2D. Every time I press the left mouse button a box should be displayed at the click coordinates. But the problem is that the box is displayed to the right of the click.
Here is the code:
#include <SFML/Graphics.hpp>
#include <Box2D/Box2D.h>
static const double SCALE = 32.0;
void createBox(b2World& world, double mouseX, double mouseY);
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML 2.2", sf::Style::Close);
window.setFramerateLimit(60);
sf::RectangleShape shape;
shape.setFillColor(sf::Color::Red);
shape.setSize(sf::Vector2f(16.0, 16.0));
b2Vec2 gravity(0.0, 9.8);
b2World world(gravity);
world.SetGravity(gravity);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
{
double mouseX = sf::Mouse::getPosition().x;
double mouseY = sf::Mouse::getPosition().y;
createBox(world, mouseX , mouseY);
}
}
window.clear();
for (b2Body* bodyIterator = world.GetBodyList(); bodyIterator != 0; bodyIterator = bodyIterator->GetNext())
{
if (bodyIterator->GetType() == b2_dynamicBody)
{
shape.setPosition(SCALE * bodyIterator->GetPosition().x, SCALE * bodyIterator->GetPosition().y);
shape.setRotation(bodyIterator->GetAngle() * 180 / b2_pi);
window.draw(shape);
}
}
world.Step(1/60.0, 8, 3);
window.display();
}
return 0;
}
void createBox(b2World& world, double mouseX, double mouseY)
{
b2BodyDef bodyDef;
bodyDef.position = b2Vec2(mouseX / SCALE, mouseY / SCALE );
bodyDef.type = b2_dynamicBody;
b2Body* body = world.CreateBody(&bodyDef);
b2PolygonShape box;
box.SetAsBox(16.0 / SCALE, 16.0 / SCALE);
b2FixtureDef fixtureDef;
fixtureDef.density = 1.5;
fixtureDef.friction = 0.7;
fixtureDef.shape = &box;
body->CreateFixture(&fixtureDef);
}