使用Three.js生成正多边形

Eri*_*ric 5 javascript geometry polygon three.js

我正在使用Three.js 基于用户提供的边数来程序生成常规N字符.长期目标是将其作为渲染多面体棱镜的第一步.

我正在使用此处讨论的解决方案来计算N字形的顶点.

然后我使用这里讨论的技术在N -gon 上生成面.

我第一次尝试生成必要的Geometry对象导致以下内容,在添加到Mesh后似乎没有呈现任何内容:

function createGeometry (n, circumradius) {

    var geometry = new THREE.Geometry(),
        vertices = [],
        faces = [],
        x;

    // Generate the vertices of the n-gon.
    for (x = 1; x <= n; x++) {
        geometry.vertices.push(new THREE.Vector3(
            circumradius * Math.sin((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            circumradius * Math.cos((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            0
        ));
    }

    // Generate the faces of the n-gon.
    for (x = 0; x < n-2; x++) {
        geometry.faces.push(new THREE.Face3(0, x + 1, x + 2));
    }

    geometry.computeBoundingSphere();

    return geometry;
}
Run Code Online (Sandbox Code Playgroud)

经过长时间的玩弄后,我发现了ShapeGeometry类.它使用与上例相同的顶点算法,但是这个算法在添加到Mesh后正确呈现:

function createShapeGeometry (n, circumradius) {

    var shape = new THREE.Shape(),
        vertices = [],
        x;

    // Calculate the vertices of the n-gon.                 
    for (x = 1; x <= sides; x++) {
        vertices.push([
            circumradius * Math.sin((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            circumradius * Math.cos((Math.PI / n) + (x * ((2 * Math.PI)/ n)))
        ]);
    }

    // Start at the last vertex.                
    shape.moveTo.apply(shape, vertices[sides - 1]);

    // Connect each vertex to the next in sequential order.
    for (x = 0; x < n; x++) {
        shape.lineTo.apply(shape, vertices[x]);
    }

    // It's shape and bake... and I helped!         
    return new THREE.ShapeGeometry(shape);
}
Run Code Online (Sandbox Code Playgroud)

使用ShapeGeometry示例解决的几何示例有什么问题?

我不认为这是相机或定位的问题,因为用更简单的整数替换复杂的顶点计算会产生没有问题的多边形,前提是这些值是有意义的.

我问的原因是因为,正如我最初提到的,我想最终将它作为渲染多面体的第一步.ShapeGeometry对象可以挤出来给他们的深度,但即便如此three.js所使可用的选项,这可能是不够的我,从长远来看需求所需的多面体变得更加不规则.

有什么想法吗?

Lee*_*ski 5

您可以使用THREE.CylinderGeometry创建棱镜; 对于n面棱镜,你可以使用

// radiusAtTop, radiusAtBottom, height, segmentsAroundRadius, segmentsAlongHeight
var nPrism = new THREE.CylinderGeometry( 30, 30, 80, n, 4 );
Run Code Online (Sandbox Code Playgroud)

您还可以使用CylinderGeometry创建金字塔和平截头体; 有关内置形状的更多示例,您可以查看:

http://stemkoski.github.io/Three.js/Shapes.html

既然您也可能对更多普通的多面体感兴趣,您可能还想看看:

http://stemkoski.github.io/Three.js/Polyhedra.html

其中包括柏拉图固体,阿基米德固体,棱镜,反棱镜和约翰逊固体的模型; 然而,在该程序中,多边形是"厚"的,因为使用球体作为顶点,使用圆柱作为边缘.

希望这可以帮助!


Ele*_*ant 2

您的函数按预期工作。

看看这个小提琴http://jsfiddle.net/Elephanter/mUah5/

there is a modified threejs fiddle with your createGeometry function
Run Code Online (Sandbox Code Playgroud)

所以你在另一个地方遇到问题,而不是在 createGeometry 函数上