OpherV
OpherV

Reputation: 6937

How do I make an object perpendicular to a face with Three.js?

Relevant codepen:

http://codepen.io/OpherV/pen/yNebep

In my game I have a model of an alien tree. For each face of this tree I generate a pyramid (CylinderGeometry with 4 faces), and position it at the center of the face. Then I wish for this pyramid to be perpendicular to the face, so that I'll get a tree with spikes. I've tried achieving this with object.lookAt and point it at the face normal, but weird things happen. For example:

enter image description here

If I add

cylinderGeometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );

The shape in the middle works as expected, but the rest is still distorted enter image description here

What is the proper way to get my spiked tree?

Bonus question

How would I go about merging these spikes to the original geometry after proper creation and orientation so that I don't have so many separate objects?

Upvotes: 0

Views: 1845

Answers (1)

WestLangley
WestLangley

Reputation: 104793

You want to create cylinder and point it in a particular direction. One way to do that is to use the following pattern:

Create the geometry.

var cylinderGeometry = new THREE.CylinderGeometry( 1, 10, 25, 4, 1 );

Translate the geometry so the base sits at the origin.

cylinderGeometry.translate( 0, 12.5, 0 );

Rotate the geometry so the top points in the direction of the positive-Z axis.

cylinderGeometry.rotateX( Math.PI / 2 );

Create the mesh.

var cylinder = new THREE.Mesh( cylinderGeometry , characterSkinMaterial );

Objects in three.js are by default "looking" in the direction of their local positive-Z axis. (Except the camera, which looks down its negative-Z axis.)

Tell the cylinder to "look" in the direction you want. Since we have transformed the geometry, this will make the top of the cylinder point in the desired direction.

cylinder.lookAt( face.normal ); 

Now place the cylinder wherever you want it.

cylinder.position.copy( centerPoint );              

obj.add( cylinder );

three.js r.91

Upvotes: 2

Related Questions