If you're looking to align a cylinder using a transformation matrix, here's an example code snippet to help you out:
function createCylinderFromEnds( material, radiusTop, radiusBottom, top, bottom, segmentsWidth, openEnded)
{
// defaults
segmentsWidth = (segmentsWidth === undefined) ? 32 : segmentsWidth;
openEnded = (openEnded === undefined) ? false : openEnded;
// Dummy settings, replace with your own code:
var length = 100;
var cylAxis = new THREE.Vector3(100,100,-100);
var center = new THREE.Vector3(-100,100,100);
var cylGeom = new THREE.CylinderGeometry( radiusTop, radiusBottom, length, segmentsWidth, 1, openEnded );
var cyl = new THREE.Mesh( cylGeom, material );
// apply transformation to align with given axis and move to center
makeLengthAngleAxisTransform( cyl, cylAxis, center );
return cyl;
}
// Function to transform cylinder to align with given axis and move to center
function makeLengthAngleAxisTransform( cyl, cylAxis, center )
{
cyl.matrixAutoUpdate = false;
// Translate first before rotating
cyl.matrix.makeTranslation( center.x, center.y, center.z );
var yAxis = new THREE.Vector3(0,1,0);
cylAxis.normalize();
var rotationAxis = new THREE.Vector3();
rotationAxis.crossVectors( cylAxis, yAxis );
if ( rotationAxis.length() < 0.000001 )
{
rotationAxis.set( 1, 0, 0 );
}
rotationAxis.normalize();
var theta = -Math.acos( cylAxis.dot( yAxis ) );
var rotMatrix = new THREE.Matrix4();
rotMatrix.makeRotationAxis( rotationAxis, theta );
cyl.matrix.multiply( rotMatrix );
}
This code snippet is part of the Chapter 5: Matrices in the free Interactive 3D Graphics course available here. You can find the full working sample on GitHub.
If you are new to transformations, I recommend starting with Chapter 4 before diving into this.
Another tip is to use Matrix4's lookAt()
method for rotation and adjusting the translation pivot point before applying the matrix to the cylinder.