【问题标题】:Three.js cylinder rotation in 3d planeThree.js 圆柱在 3d 平面上的旋转
【发布时间】:2013-07-29 16:50:24
【问题描述】:

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

我一直无法获得角度。我想让圆柱体旋转,这样找到的角度就会使圆柱体连接两点。

基本上我正在尝试找到一种方法来找到 (x1,y1,z1) 和 (x2,y2,z2) 之间的角度。并让它修改一个圆柱体(圆柱体.rotation.x、圆柱体.旋转.y和圆柱体.旋转.z)。

【问题讨论】:

标签: javascript three.js


【解决方案1】:

您可以使用转换矩阵来做到这一点。下面是一些示例代码:

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 章的一部分:来自这个很棒的免费 Interactive 3D Graphics course 的矩阵,使用 three.js 教授。

我强烈推荐它。如果您没有机会尝试转换,您可能希望从第 4 章开始。

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

【讨论】:

  • 感谢 Udacity 链接!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-20
  • 2017-01-13
  • 2012-02-20
  • 1970-01-01
相关资源
最近更新 更多