Search code examples
vectorrotationthree.jsquaternions

three.js rotate object by an axe direction


I want to rotate a cylinder in a certain axe made by two points p1 and p2. I create the cylinder with the height l equal to the distance between the two points, I place it in the middle of that axe.

var xd = p2.x - p1.x,
yd = p2.y - p1.y,
zd = p2.z - p1.z,
l = Math.sqrt(xd*xd + yd*yd + zd*zd);
var cylinder = new THREE.Mesh( new THREE.CylinderGeometry( 5, 5, l, 32 ), new THREE.MeshBasicMaterial( {color: "#ffffff"} ) );
cylinder.position.set(p1.x+xd/2, p1.y+yd/2, p1.z+zd/2);

I use setFromUnitVectors to get the rotaion matrix needed between the two points and apply it to the rotation matrix of the cylinder

var quaternion = new THREE.Quaternion();
quaternion.setFromUnitVectors(new THREE.Vector3(p1.x,p1.y,p1.z).normalize(),new THREE.Vector3(p2.x,p2.y,p2.z).normalize());
cylinder.rotation.setFromQuaternion(quaternion);

I dont see what is wrong or maybe there is another way to do it?


Solution

  • another way to do this is to just make the cylinder LookAt(p2) if p2 is a vector.