Threejs几何和TypeScript [英] Threejs Geometry and TypeScript
问题描述
我想为网格顶点和面编写正确的类型.
I would like to write correct types for the Mesh Vertices and Faces.
在第一个示例中,我创建了一个新的网格,当我想从几何图形访问顶点和面时,会出现一些错误:
In the first example, I create a new Mesh, and when I want to access Vertices and Faces from geometry, I get a few errors:
const material = new THREE.MeshLambertMaterial({color: 0x00ff00});
const geometry = new THREE.Geometry();
const newMesh = new THREE.Mesh(geometry, material);
scene.add(newMesh);
const { vertices, faces } = newMesh.geometry;
// Error: Property 'vertices' does not exist on type 'BufferGeometry | Geometry'
// Error: Property 'faces' does not exist on type 'Geometry | BufferGeometry'.
newMesh.geometry.colorsNeedUpdate = true;
// Error: Property 'colorsNeedUpdate' does not exist on type 'Geometry | BufferGeometry'.
在第二个示例中,我从场景中获取网格,然后得到以下错误:
In the second example, I get Mesh from the Scene, and then I get the following error:
const mesh = scene.getObjectByName('boxMesh');
const geometry = mesh.geometry;
// Property 'geometry' does not exist on type 'Object3D'.
推荐答案
通过网格( newMesh.geometry
)访问几何,您将得到的几何类型类似于 geometry
属性在Mesh类上.显然,该属性支持两种不同类型的几何,因此您可以得到一个并集: Geometry |BufferGeometry
.
By accessing the geometry via the mesh (newMesh.geometry
) you get the geometry typed like the geometry
property on the Mesh class. Apparently the property supports two different types of geometry so you get a union: Geometry | BufferGeometry
.
如果您确切知道使用了哪种几何类型,则只需声明属性值的类型即可:
If you know exactly what type of geometry is used you can just assert the type of the property value:
const { vertices, faces } = <THREE.Geometry>newMesh.geometry;
如果您不知道 geometry
的类型,则需要一些条件逻辑,例如使用类似的东西:
If you do not know the type of geometry
you need some conditional logic, e.g. using something like:
const geometry = newMesh.geometry;
if (geometry instanceof THREE.Geometry)
// geometry will be typed as Geometry here
else
// geometry will be typed as BufferGeometry here
在第二种情况下,您使用 getObjectByName
,它总是返回最基本类型的对象 Object3D
.在这里,您还必须相应地声明结果的类型.
In the second case you use getObjectByName
which always returns objects of the most basic type Object3D
. Here you also have to assert the type of the result accordingly.
// Assuming the thing named boxMesh is a Mesh...
// The <any> assertion prevents additional type errors.
const mesh = <THREE.Mesh><any>scene.getObjectByName('boxMesh');
这篇关于Threejs几何和TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!