Issue aligning faces in Three.JS from two seperate objects

1k views Asked by At

I'm having an issue in my three.js code.

I am trying to align two objects by selecting two faces and have the second face (and object) rotate to match the normal vector of the first object's selected face.

So far I have:

var normalMatrix = new THREE.Matrix3().getNormalMatrix( object.matrixWorld );
var worldNormal = face.normal.clone().applyMatrix3( normalMatrix ).normalize();
var normalMatrixRef = new THREE.Matrix3().getNormalMatrix( objectRef.matrixWorld );
var worldNormalRef = faceRef.normal.clone().applyMatrix3( normalMatrixRef).normalize();

where: object is my object that will be rotated, face is the selected face of that object, objectRef is the stationary object reference and faceRef is the normal of the object I want to match.

Prior to doing

  object.lookAt(worldNormalRef);

, I am trying either

object.up = new THREE.Vector3(0,0,1); 
object.up = worldNormal;
object.up = face.normal; 

and neither work.

Either object.up cases are not working as they should. When I do the action, the target object (the one to be rotated) does rotate, but does not align the faces correctly. It is arbitrary but somehow is linked to objects current rotation (ie: sometimes it rotates along (0,1,0) or simliar, othertimes if I pre-rotate the object it just rotates a slight bit.

In theory lookAt uses a world vector which my faceRef is, and as long as I set the 'up' correctly, it should work but it dosen't.

Any ideas?

1

There are 1 answers

0
jonnycowboy On

I found the issue in my code, I hope it can help somebody in the future. The

object.lookAt(worldNormalRef); 

needs instead to be modified to add the new face normals to the current object's postition for the lookAt to function correctly:

//create a point to lookAt
var newPoint = new THREE.Vector3(
    object.position.x + worldNormalRef.x,
    object.position.y + worldNormalRef.y,
    object.position.z + worldNormalRef.z
);

object.up = face.normal;//Z axis up
object.lookAt(newPoint ); 

Also note that the object.up should be set as above to the face.normal (the face I want to align to the reference object's face), and not to the worldNormal set above (I will delete this part of my code).