问题
Question is simple so, no codes! If someone knows Box2D and SDL2, then, please tell me how to wrap SDL_Rect with b2body. Ofcourse, it requires to know the conversion of metre to pixel and vice versa. This is because Box2D measures distance in metres. Can you give me a simple expression or function to convert metres(of Box2D) to pixels or pixels to metres(of Box2D)?
回答1:
Can you give me a simple expression or function to convert metres(of Box2D) to pixels or pixels to metres(of Box2D)?
Unfortunately, this isn't as simple as it sounds, for us. Because, if your game is on worms, then your game world would be in millimetres while if it's like Space Invaders then it would be in kilometres? So it's up to the game designer to decide this scaling factor. Without knowing about the intricacies of the game, deducing this factor would just be a wild guess at best.
From Box2D's faq:
How do I convert pixels to meters?
Suppose you have a sprite for a character that is 100x100 pixels. You decide to use a scaling factor that is 0.01. This will make the character physics box 1m x 1m. So go make a physics box that is 1x1. Now suppose the character starts out at pixel coordinate (345,679). So position the physics box at (3.45,6.79). Now simulate the physics world. Suppose the character physics box moves to (2.31,4.98), so move your character sprite to pixel coordinates (231,498). Now the only tricky part is choosing a scaling factor. This really depends on your game. You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot.
Here the scaling factor is what you set; your decision on how many pixels would constitute one unit of your game world.
It is usually recommended that you do all the calculations in the game world units and finally, as a last step (render), do the conversion to pixels; likewise before bringing in data from outside (say an image/sprite, which is in pixels) to the world space, do the reverse conversion only once and then deal in world units in the rest of the code. See this article by Erin Catto, Box2D's author, on this issue. An excerpt:
You should consider using MKS units in your game code and just convert to pixels when you render. This will simplify your game logic and reduce the chance for errors since the rendering conversion can be isolated to a small amount of code.
This paragraph appears in the manual too.
回答2:
2 pixels a meter? This is a pretty big game world. Ignore DPI. This is completely confusing the issue IMO. Simplest : You model in real world coordinates (box2d does on meters) and you map, in libgdx terminology, via a viewport at rendering. If you make your game world too small there may be problems with vertices collisions however.
来源:https://stackoverflow.com/questions/28028121/how-many-pixels-is-a-meter-in-box2d