繁体   English   中英

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

[英]Best way to get vertices of a mesh three.js

我是Three.js的新手,所以也许我并没有达到最佳状态,

我有如下创建的几何图形,

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

然后我对其进行旋转

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

然后我从中创建一个网格

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中的。

任何提示和代码示例将不胜感激。

我认为您被有关Three.js对象的某些语义所绊倒。

1) Mesh没有顶点。 Mesh包含对Geometry / BufferGeometryMaterial引用。 顶点包含在Meshgeometry属性/对象中。

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

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

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

    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]);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM