Yes i figured out actually. The logic behind this scene is this. You cannot actually attach a sprite to a box2d body. But what you can do is at every frame,
update the position of the sprite with the position of the actual body. And whatever movements the box2d body will do, so the sprite will do.
When the body stops moving so the sprite will stop moving.
So for example you have a dynamic body that falls to the ground. You specify the size of the body to match the size of your sprite, and in the Update functions
you set the position of the sprite by getting the position of the box2d body. A pseudocode for this :
sprite.setPosition(body->GetPosition().x * scaleFactor, body->getPosition().y * scaleFactor);
The sprite will move according to the box2d body movement. And if you match the size of the body with the size of the sprite
you can have objects collide at the exact spots, and thus you would have a visual representation of the box2d physics bodies.
Since box2d has different type of bodies i made structures for each one of them so i can create vectors
when making tiles, and during map reading process i push back new object of the structures according to the tile position and size.
struct BoxStatic
{
b2BodyDef BodyDef;
b2Body *Body;
b2PolygonShape Shape;
b2FixtureDef FixtureDef;
BoxStatic(float x, float y, int w, int h);
};
struct BoxDynamic
{
b2BodyDef BodyDef;
b2Body *Body;
b2PolygonShape Shape;
b2FixtureDef FixtureDef;
BoxDynamic(float x, float y, int w, int h);
};
In the map parser function
for(int i = 0; i < mapHeight; i++){
for(j = 0; i < mapWidth; j++){
m_collisionCoords.push_back(new BoxStatic(j * tileWidth, i * tileHeight, tileWidth, tileHeight));
}
}
in the map show function
for(int i = 0; i < mapHeight; i++){
for(j = 0; i < mapWidth; j++){
sprite->setPosition(m_collisionCoords[j]->Body->GetPosition().x * scaleFactor, m_collisionCoords[i]-Body->GetPosition().y * sca leFactor);
}
}
So the logic is to attach sprite position to the box2d body position. And when making tiles you read all coordinates from the
file, push back new struct object for each tile you read from file with size and position to match the tile.
Hope this helps somebody to grasp the logic behind making sfml sprites behave based on box2d physics bodies.