几何体、顶点、索引、面
在 Three.js 中,几何体确定了一个物体的形状,材质决定了一个物体的外观。
在上一节中,切换到线框模式的时候,可以发现正方体是由多个三角形构成的,这是因为在 Three.js 中,所有的物体都是由三角形构成的。
在一个正方体中,一个面由 4 个顶点构成,总共有 6 个面,所以一共有 24 个顶点。
可以打印几何体的顶点:
console.log(cube.geometry)
查看几何体的顶点坐标和数量:
创建一个最原始的三角形几何体:
// 创建几何体
const geometry = new THREE.BufferGeometry()
// 创建顶点数据
const vertices = new Float32Array([
1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
])
// 设置几何体顶点
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3))
// 创建材质
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
})
// 创建网格
const mesh = new THREE.Mesh(geometry, material)
// 添加到场景
scene.add(mesh)
注意,顶点是有顺序的,逆时针为正面,顺时针为背面。
如果不需要区分,可以设置 side: THREE.DoubleSide
。
const material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
side: THREE.DoubleSide,
})
接下来绘制正方形,如果用上述的三角形,需要绘制 2 个三角形,也就是 6 个顶点:
const vertices = new Float32Array([
1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
1.0, 1.0, 0.0,
-1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
])
但其中只有 4 个顶点是有效的,其余的顶点是重复的。
所以需要使用索引,来减少顶点的数量。
// 使用索引
const vertices = new Float32Array([
1.0, 1.0, 0.0,
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
])
geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3))
const indices = new Uint16Array([
0, 1, 2,
0, 3, 1,
])
geometry.setIndex(new THREE.BufferAttribute(indices, 1))
本节示例代码:https://github.com/wukaipeng-dev/threejs-demo/blob/main/02-basic/src/main-vertices.ts