Three.js在3d平面中的圆柱体旋转

时间:2013-07-29 18:46:29

标签: javascript three.js

我一直有线宽问题(与窗口上的ANGLE有关)。我已经使用了2点之间的圆柱体(在3D空间中)。我已经解决了根据2点3D距离公式获得圆柱长度的问题。

我一直遇到麻烦但是得到角度。我希望圆柱体旋转,以便找到的角度使圆柱体连接两个点。

本质上我试图找到一种方法来找到(x1,y1,z1)和(x2,y2,z2)之间的角度。并修改一个圆柱体(cylinder.rotation.x,cylinder.rotation.y和cylinder.rotation.z)。

1 个答案:

答案 0 :(得分:2)

您可以使用转换矩阵来执行此操作。这是一些示例代码:

function createCylinderFromEnds( material, radiusTop, radiusBottom, top, bottom, segmentsWidth, openEnded)
{
    // defaults
    segmentsWidth = (segmentsWidth === undefined) ? 32 : segmentsWidth;
    openEnded = (openEnded === undefined) ? false : openEnded;

    // Dummy settings, replace with proper 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 );

    // pass in the cylinder itself, its desired axis, and the place to move the center.
    makeLengthAngleAxisTransform( cyl, cylAxis, center );

    return cyl;
}

// Transform cylinder to align with given axis and then move to center
function makeLengthAngleAxisTransform( cyl, cylAxis, center )
{
    cyl.matrixAutoUpdate = false;

    // From left to right using frames: translate, then rotate; TR.
    // So translate is first.
    cyl.matrix.makeTranslation( center.x, center.y, center.z );

    // take cross product of cylAxis and up vector to get axis of rotation
    var yAxis = new THREE.Vector3(0,1,0);
    // Needed later for dot product, just do it now;
    // a little lazy, should really copy it to a local Vector3.
    cylAxis.normalize();
    var rotationAxis = new THREE.Vector3();
    rotationAxis.crossVectors( cylAxis, yAxis );
    if ( rotationAxis.length() < 0.000001 )
    {
        // Special case: if rotationAxis is just about zero, set to X axis,
        // so that the angle can be given as 0 or PI. This works ONLY
        // because we know one of the two axes is +Y.
        rotationAxis.set( 1, 0, 0 );
    }
    rotationAxis.normalize();

    // take dot product of cylAxis and up vector to get cosine of angle of rotation
    var theta = -Math.acos( cylAxis.dot( yAxis ) );
    //cyl.matrix.makeRotationAxis( rotationAxis, theta );
    var rotMatrix = new THREE.Matrix4();
    rotMatrix.makeRotationAxis( rotationAxis, theta );
    cyl.matrix.multiply( rotMatrix );
}

我没写这个。找到完整的工作样本here。 它是第5章的一部分:使用three.js教授的这个令人敬畏的免费Interactive 3D Graphics course的矩阵。

Interactive 3D Graphics course

我热烈推荐它。如果您没有机会玩转换,可能需要从第4章开始。

作为旁注。您也可以作弊并使用Matrix4的lookAt()来解决旋转,偏移平移,使枢轴位于圆柱体的尖端,然后将矩阵应用于圆柱体。