Alex1231
Alex1231

Reputation: 43

Generate shape in three.js from multiple elements

Is there a way in three.js to create a poly from multiple individual elements, rectangle for example.

I have attached an example.

I am using:

                for(i = 0; i<5; i++){                           


                        var rand = Math.floor(Math.random() * 50)+1000;

                            var material = new THREE.MeshBasicMaterial({
                                color : "#ff"+i+ rand,

                                side : THREE.DoubleSide,
                                transparent : true,
                                opacity : 1
                            });


                            var mesh = new THREE.Mesh( geometry, material );


                            if(angle) mesh.rotation.y = angle;


                            mesh.position.set( loop+1, 4,4);

                            scene.add( mesh ); 

                    }

When I apply roatation mesh.rotation.y = angle; it doesn't come up with my below design, I rather get a cross + because the panel rotates on it's y from center, not from corner...

Thank you

The enter image description here

Upvotes: 0

Views: 68

Answers (1)

travnik
travnik

Reputation: 730

There are 3 ways to achieve what you're trying to do. The problem you are facing stems from transform origin, as you noted, origin defaults to position [0,0,0]. So, your options are:

  • build a transform matrix using a different transform offset for rotation, this is probably an overkill for simple use-cases.
  • translate geometry to not be centered on [0,0,0], for example you can move the whole quad (your geometry) right so that the left edge of the quad aligns with [0,0,0], then, when you rotate, left edge will stay put.
  • embed Mesh inside a Group, rotate the Mesh and translate (position.set(....)) the Group.

no matter which route you take - you will still have to deal with the some trigonometry as you will need to compute the position for the next segment to align with the edge of the previous one.

One more way around that is to build the following type of structure

Group[ 
   Mesh 1, 
   Mesh 2, 
   Mesh 3, 
   Group [
     Mesh 4,
     Mesh 5,
     Mesh 6,
     Group [
        Mesh 7
     ]
   ]
]

Last group is unnecessary, it's there purely for consistency.

As far as the trigonometry that I mentioned - it's simple Sin and Cos stuff, so it should be quite simple. Here is some pseudo-code that you'll need:

prevPosition, prevAngle //position and angle of previous segment
// Compute next segment transform
nextPosition.x = Math.cos(prevAngle)*segmentSize + prevPosition.x;
nextPosition.z = Math.sin(prevAngle)*segmentSize + prevPosition.z;

Upvotes: 1

Related Questions