three.js -- 几何图形Geometries

371 阅读1分钟

通过三维向量自定义图形

// 1、创建一个空的几何图形
const geometry = new THREE.Geometry()

// 2、创建三维向量(就是通过x,y,z确定一个三维空间的点)
// 将这个点push进空的几何图形的点(三个点确定一个面,所以创建了三个点)
const vertex1 = new THREE.Vector3(0, 0, 0);
geometry.vertices.push(vertex1)

const vertex2 = new THREE.Vector3(0, 1, 0);
geometry.vertices.push(vertex2)

const vertex3 = new THREE.Vector3(1, 0, 0);
geometry.vertices.push(vertex3)

// 3、创建面的顶点(确定这是面从那个点开始画)
// 将顶点push进几何图形的面中
const face = new THREE.Face3(0, 1, 2)
geometry.faces.push(face)

缓冲几何(推荐使用,性能更佳)

const geometry = new THREE.BoxBufferGeometry(1,1,1,2,2,2)

// 通过js创建32位浮点数的数组
const positiionsArray = new Float32Array([
  0, 0, 0,
  0, 1, 0,
  1, 0, 0
])

// 存储与缓冲几何有关的数据(如:顶点位置向量,面片索引,法向量,颜色值,uv坐标等)
// 当前只存储了顶点位置, 3是,将数组中每三为作为一个分割点
const positionAttribute = new THREE.BufferAttribute(positionArray, 3)

// 创建缓冲几何
const geometry = new THREE.BufferGeometry()
// 给空的缓冲几何设置顶点 版本差异使用的是 addAttribute
geometry.setAttribute('position', positionAttribute)

创建多个三角形

const geometry = new THREE.BufferGeometry();

const count = 50
// 50个三角形,每个三角形有三个点,一个点由3个值确定
const positionArray = new Float32Array(count * 3 * 3)

// 给每个点设置一个随机数,生成随机三角形
for(let i = 0; i < count*3*3; i++) {
	positionArray[i] = Math.random() - 0.5
}

// 将数组放入缓冲几何链接中
const positionAttribute = new THREE.BufferAttribute(positionArray, 3)
geometry.setAttribute('position', positionAttribute)

对于优化,我们可以使用index,比如一个面有多个三角形组成,但是中间这个点可以作为多个三角形的顶点使用

这样可以减少发送给gpu的数据,优化性能