How to properly scale Box2D units to correctly display sprite?

Hi,

Recently got Box2D working and have been using a 1:1 scale.(1meter = 1pixel)
Now that was a very bad idea, as it seemed like a cube was falling only a few meteres, but in reality, it was falling more that 500 meters.
So I want to implement some scaling system that correctly sets the position of my sprite based on the location and rotation of the Box2D object.
Now I have problems doing that, as setting the Box2D object to half the size, and multiplying the x and y of the sprite by 2 only offsets the object.
Leaving the sprite x and y to straight Box2D units makes it render fine, at the correct positions, but makes the object stick half throught the ground, as the collision is smaller then the sprite.

So how would I match the Box2D collision size(Object) to match the size of my sprite by scaling?(so I dont need a 64x64 meters object to have a 64x64 sprite)
The functions my renderer(SFML) provides are :

Code: Select all

SetPosition() and,
SetAngle() and,
SetScale() / not nescecessy for what I want as i want to keep it the original size)

This thus means that I can't alter vertices directly.(May that be nescecerry for whatever)

Can someone explain me how I achieve what I want?


Thanks! 😀
Let say your sprite is 64*64 box and your box is 2 meters large. your ratio is 32 here (64/2). (if you want several sizes of sprites being 2 meters large you'll have to add a scale for the sprite itself. But let's say all your sprite have a ratio of 32 compared to physics

now let's say you camera zoom factor is 1, you are not zooming nor unzooming. (of zomm was <>1 this would add another factor of course)

-you get the position of your box in physics (in meter)
boxPosition=myBoxb2Body.GetPosition()
-Multiply the vector by the scalar ration, you'll get the position in pixel
boxPosition.x=boxPosition.x*32
boxPosition.y=boxPosition.y*32

now you can draw your sprite without modifying it's scale.
SetPosition(boxPosition)

I can give you a more complete answer (with any sprite size and zoom/unzoom) but it's now a bit long you asked the question so may be you found the answer somwhere else.

Original thread: https://box2d.org/forum/viewtopic.php?t=10289