three.js学习笔记5:几何图形

70 阅读2分钟

几何体

所有几何图形都继承自BufferGeometry类,这个类上有很多方法:translate(),rotateX()等,所有可实例化的各种形状的几何体的类在three.js文档中,可以直接查到:

BoxGeometry:长方体

CapsuleGeometry:椭圆 ......

BoxGeometry

通过长方体讲一下他的六个参数和细分的概念

BoxGeometry有6个参数:

  1. width:在x轴上的大小
  2. height:在y轴上的大小
  3. depth:在z轴上的大小
  4. widthSegments:在x轴上的细分数量
  5. heightSegments:在y轴上的细分数量
  6. depthSegments:在z轴上的细分数量

细分是一个面上有多少个三角形组成:一个长方形面对角顶点相连可以形成两个三角形,将轴进行细分,就能获得更多的三角形,这有助于更方便的对细节操作,比如一个面上有多个小三角形,对其中某个顶点向上提,则三角形越小,向上提的部分就越精确,越细节,这张平面就会有高低之分。

IMG_1829.PNG 可以在mesh网格的材料中设置显示线框结构

const material=new THREE.MeshBasicMaterial({
    color:"#ff0000",
    wireframe:true
})

K{ACLTNTEMY8DB_3P%}MC.png

创建自己的图形

在创建一个自己定义的几个图形前,先了解如何存储BufferGeometry数据,这个数据包括顶点,位置,uv,nomal等

  1. 使用原生js的语法Float32Array创建这些数据,是一个一维数组,只能存储浮点数,有固定长度

创建数组有两种方法:

方法一:

//长度为9的数组
const positionsArray=new Float32Array(9);
//第一个顶点,xyz轴的值
positionsArray[0]=0;
positionsArray[1]=0;
positionsArray[2]=0;
//第二个顶点
positionsArray[3]=0;
positionsArray[4]=1;
positionsArray[5]=0;
//第三个顶点
positionsArray[6]=1;
positionsArray[7]=0;
positionsArray[8]=0;

方法二:

const positionsArray=new Float32Array([
    0,0,0,
    0,1,0,
    1,0,0
])
  1. 将数据数组形式转为要存储的three.js中的BufferAttribute形式,第一个参数是转化的数组,第二个参数是一个顶点有几个轴的值确定
const positionsAttribute=new Three.BufferAttribute(positionsArray,3)
  1. 创建一个空的BufferGeometry
const geometry=new THREE.BufferGeometry()
  1. 将位置属性放入图形中,告知其组成图形的几个点
geometry.setAttribute("position",positionsAttribute)

IV~Q}8NUMB9N8JPNO.png

创建50个随机顶点的三角形,定点取值范围为-0.5~0.5

const count=50;
//50个三角形,每个三角形3个顶点,每个顶点由3个坐标决定
const positionsArray=new Float32Array(count*3*3)
for(let i=0;i<count*3*3;i++){
    positionsArray[i]=Math.random()-0.5
}
const positionsAttribute=new THREE.BufferAttribute(positionArray,3)
const geometry=new THREE.BufferGeometry()
geometry.setAttribute("position",positionsAttribute)
const material=new THREE.MashBasicMaterial({
    color:"#ff0000",
    wireframe:true
})
......

E4IRZXZ40WL0BA91ARF47.png