Saturnix
Saturnix

Reputation: 10564

Rendering box2d rectangle as a 3d rectangle in three.js

When rendering box2d bodies with the canvas, there's the big problem that box2d can only gives us the centre of the body and its angle (while the canvas draws shapes like rectangles from the top-left angle). By looking at some tutorials from Seth Land I've bypassed this problem and now works fine (I would never been able to figure out something like this by myself):

g.ctx.save();
g.ctx.translate(b.GetPosition().x*SCALE, b.GetPosition().y*SCALE);
g.ctx.rotate(b.GetAngle());
g.ctx.translate(-(b.GetPosition().x)*SCALE, -(b.GetPosition().y)*SCALE);
g.ctx.strokeRect(b.GetPosition().x*SCALE-30,b.GetPosition().y*SCALE-5,60,10);
g.ctx.restore();

where b is the body, SCALE is the canvas-pixel/box2d-meters converter, 60 and 10 are the dimensions of the rectangle (so 30 and 5 are the half dimensions).

_

The problem

Now, I would like to render this on three.js. First objection is that three.js works in 3d while box2d doesn't. No problem on that: I just want to build a 3d rectangle on top of the 2d one. The 2d axis dimensions must be from box2d while I want the last dimension to be totally arbitrary.

My work doesn't require 3d physics, 2d will be sufficient but I would like to give these 2d objects a thickness in the third dimension. How can I do that?! So far I've been trying like this:

   // look from above
    camera.position.set(0,1000,0);
    camera.rotation.set(-1.5,0,0);

    geometry = new THREE.CubeGeometry( 200, 60, 10 , 1,1,1);

    // get b as box2d rectangle
    loop(){
    mesh.rotation.y = -b.GetAngle();
    mesh.position.x = b.GetPosition().x*SCALE;
    mesh.position.y = -b.GetPosition().y*SCALE;
    }

Unfortunately, this doesn't look as the box2d debug draw at all. -1.5 is not the right value to turn the camera of a perfect 90 degree angle (does anyone know the exact value?) and, even worst, the three.js rectangle doesn't follow the box2d movements, having almost the same problems I had with the standard canvas before using context translate and context rotation.

I hope anyone have time to explain a possible solution. Thanks a lot in advance! :)

EDIT: it looks someone did it already (requires webgl on chrome): http://game.2x.io/ http://serv1.aelag.com:8082/threeBox

The second one are just spheres so no problem on the rotation mapping between box2d and threejs. The first one also includes cubes and rectangles: that what I'm trying to do.

Upvotes: 1

Views: 2464

Answers (1)

sole
sole

Reputation: 2077

What type of camera are you using?

For getting a "2d" effect you need to use an Orthographic camera, otherwise you will get perspective-projected stuff and things won't match with what you're seeing in 2D.

Upvotes: 1

Related Questions