threejs - 基础几何体

82 阅读1分钟

BufferGeometry

Three.js中的BufferGeometry是一种高效的几何体表示方式,它直接操作底层的顶点数据(如位置、颜色、法线等),这种方式相比传统的几何体类(如BoxGeometrySphereGeometry等)更为高效,尤其是在处理大量几何数据或需要自定义顶点数据时。

// 创建几何体
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, -1.0, 1.0, 0.0,
]);
// 创建顶点属性
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
// 创建索引
const indices = new Uint16Array([0, 1, 2, 2, 3, 0]);
// 创建索引属性
geometry.setIndex(new THREE.BufferAttribute(indices, 1))
// 创建材质
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
  side: THREE.DoubleSide,
});
const cube = new THREE.Mesh(geometry, material);

几何体划分顶点组设置不同的材质

几何体.groups([]),将当前几何体分割成组进行渲染。 分割后的每个部分都是一个如下的表单 {start: <Integer>当前几何体的第一个顶点,或者第一个三角面片的索引,count: <Integer>指明当前分割包含多少顶点,materialIndex: <Integer>指出当前用到的材质队列索引}

// 设置2个顶点组,形成2个材质
// 从0索引开始,添加3个顶点,使用第一个材质
geometry.addGroup(0, 3, 0)
geometry.addGroup(3, 3, 1)
// 创建材质
const material = new THREE.MeshBasicMaterial({
  color: 0x00ff00,
});
const material1 = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  wireframe: true
});
const cube = new THREE.Mesh(geometry, [material, material1]);