# Box2D in 3D space

I am trying to combine a perspective camera with a box2D world using libgdx and I am having some problems getting the two to synch up. I want to do this so I can use 3D models but keep the game in a fixed plane like a 2D platformer and I will not move, angle or zoom the camera. I set the Box2D world to a fixed size, say 35x20 meters. The problem I have is calculating how much I need to move the 3D models so they synch up with the Box2D world. Lest say I move the Box2D body of a character 1 meter to the left how much should I move the 3D model then?

I tried to simply calculate pixels per meter and use that to move the 3D models. But I guess that I need to take the distance from the camera into account? So if someone have a formula or can point me in the right direction on which formula to use I would really appreciate it, thanks!

• Don't use pixels, just use meters for everything? – user253751 Feb 22 '18 at 0:51

It should be pretty much the same as if you were using sprites. I would just keep it simple and say that one Box2D meter is one game unit.

• Yes, sure I have that 1 meter is one game unit. What I mean is that if I move the box2d object 1 meter and want the 3d model to be at the same place (from the cameras PoV) I need a way to convert that 1 unit to the view of the perspective camera – Andreas Toresäter Jan 1 '17 at 9:12
• @Korpen if you position the objects 1:1 in 3D space, then you'll naturally get the right perspective/foreshortening applied by the camera's view. If you distort this into the camera's projection space then you'll end up partly undoing the camera perspective so it doesn't quite look like proper 3D anymore, and also end up warping your physics in a way that will make surface contacts mismatched at some depths. Just keep a 1:1 mapping between the 2D world and a plane in your 3D world as John describes and it will work in a more expected fashion with fewer quirks to deal with. – DMGregory Apr 13 '17 at 3:36

The way I find the 3D units from pixels is by using ratios. If you want to find how far the 3D object's x is from the center of the screen then use a ratio like:

x2D = 10.0; // pixels of object from center
width2D = 60.0; // pixel width of view from center
width3D = 10.0; // 3D unit width of view from center

x3D = (x2D * width3D) / width2D


To find the 3D width use glFrustum()'s xLeft and zNear and find the z position from the modelview matrix like so:

width3D = (xLeft * z) / zNear


You can use the a / b = c / d ratio to solve for a lot of other graphics problems too, like scroll bars and radians to degrees.

Start with a bouncing ball on the ground. If it feels like moving slow, you have to increase your multiplier, say 10x. Multiply position in physics with 10 to calculate the display position and size of the ball, if that makes it feel better, it is the right constant. As long as your orthographic camera shows all of your sprite display, that can count as your resolution.