获取网格顶点的最佳方法three.js

时间:2017-11-15 20:40:02

标签: javascript three.js

我是Three.js的新手,所以也许我不会最佳地接近这个,

我创建的几何体如下,

const geo = new THREE.PlaneBufferGeometry(10,0);

然后我对它应用旋转

geo.applyMatrix( new THREE.Matrix4().makeRotationX( Math.PI * 0.5 ) );

然后我从中创建一个Mesh

const open = new THREE.Mesh( geo, materialNormal);

然后我将一组操作应用于网格以正确定位它,如下所示:

open.position.copy(v2(10,20);
open.position.z = 0.5*10

open.position.x -= 20
open.position.y -= 10
open.rotation.z = angle;

现在,在网格位置改变之前和之后获取网格顶点的最佳方法是什么?我很惊讶地发现网格的顶点没有内置到three.js中。

非常感谢任何提示和代码示例。

2 个答案:

答案 0 :(得分:2)

我认为你会因为关于three.js对象的一些语义而被绊倒。

1) Mesh没有顶点。 Mesh包含对Geometry / BufferGeometryMaterial(s)的引用。顶点包含在Mesh' s geometry属性/对象中。

2)您正在使用PlaneBufferGeometry,这意味着BufferGeometry对象的实现。 BufferGeometry将其顶点保留在position属性(mesh.geometry.attributes.position)中。请记住,顶点顺序可能会受index属性(mesh.geometry.index)的影响。

现在问题,几何原点也是它的父Mesh的原点,所以你的"在网格转换之前"顶点位置与创建网格时完全相同。按原样阅读它们。

在网格转换之后获得""在顶点位置,您需要获取每个顶点,并将其从Mesh的局部空间转换为世界空间。幸运的是,three.js有一个方便的功能:

var tempVertex = new THREE.Vector3();
// set tempVertex based on information from mesh.geometry.attributes.position

mesh.localToWorld(tempVertex);
// tempVertex is converted from local coordinates into world coordinates,
// which is its "after mesh transformation" position

答案 1 :(得分:-1)

这是一个由打字稿写的例子。

它获取了网格在世界坐标系中的位置。

    GetObjectVertices(obj: THREE.Object3D): { pts: Array<THREE.Vector3>, faces: Array<THREE.Face3> }
{
    let pts: Array<THREE.Vector3> = [];

    let rs = { pts: pts, faces: null };

    if (obj.hasOwnProperty("geometry"))
    {
        let geo = obj["geometry"];
        if (geo instanceof THREE.Geometry)
        {
            for (let pt of geo.vertices)
            {
                pts.push(pt.clone().applyMatrix4(obj.matrix));
            }
            rs.faces = geo.faces;
        }
        else if (geo instanceof THREE.BufferGeometry)
        {
            let tempGeo = new THREE.Geometry().fromBufferGeometry(geo);
            for (let pt of tempGeo.vertices)
            {
                pts.push(pt.applyMatrix4(obj.matrix));
            }
            rs.faces = tempGeo.faces;
            tempGeo.dispose();
        }
    }
    return rs;
}

if (geo instanceof THREE.BufferGeometry)
{
    let positions: Float32Array = geo.attributes["position"].array;
    let ptCout = positions.length / 3;
    for (let i = 0; i < ptCout; i++)
    {
        let p = new THREE.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
    }
}
相关问题