「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战」
网格
- 表示基于以三角形组合成的几何体的类。
three.js
中几何体是不能直接渲染的。在three.js
有一种类型物体,这种类型放入场景中才能直接渲染图形。网格(Mesh)
是这种类型中的一种。
创建使用
- 构造参数
new THREE.Mesh( geometry, material )
geometry
几何体实例。material
一个材质(material
)或多个材质(material
),多个材质对应几何体的各个面。
// 立体几何
const boxWidth = 6
const boxHeight = 6
const boxDepth = 6
const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth)
const loader = new THREE.TextureLoader()
const texture = loader.load(
'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.16pic.com%2F00%2F07%2F46%2F16pic_746871_b.jpg'
)
// 基础材质
const material = new THREE.MeshBasicMaterial({
map: texture
})
// 网格
const mesh = new THREE.Mesh(geometry, material)
mesh.position.x = 5
scene.add(mesh)
- 把定义好的几何体和材质传入,实例化网格。在放入场景中就实例化完成。
位置、缩放、旋转
- 因为
网格(Mesh)
的基类是.Object3D
。因此包含scale、rotation、position
三个属性,设置网站在场景中的位置。
.position
网格相对于父级坐标的位置。
mesh.position.x = x
mesh.position.y = y
mesh.position.z = z
.rotation
围绕x、y、z
轴旋转的弧度,需注意是弧度值。
mesh.rotation.x = x
mesh.rotation.y = y
mesh.rotation.z = z
.scale
在x、y、z
轴缩放的大小。
mesh.scale.x = x
mesh.scale.y = y
mesh.scale.z = z
使用多个材质
const loader = new THREE.TextureLoader()
const texture = loader.load( 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.16pic.com%2F00%2F07%2F46%2F16pic_746871_b.jpg'
)
const texture2 = loader.load(
'https://img2.baidu.com/it/u=363752184,2041904643&fm=253&fmt=auto&app=138&f=JPEG?w=747&h=500'
)
// 基础材质
const material = new THREE.MeshBasicMaterial({
map: texture
})
const material2 = new THREE.MeshBasicMaterial({
map: texture2
})
// 网格
const mesh = new THREE.Mesh(geometry, [material, material, material, material, material, material2])
- 通过网格的第二个参数,传入多个材质就能实现。
- 并不是所有的几何体类型都支持多种材质,立方体可以使用6种材料,每个面一个。圆锥体可以使用2种材料,一种用于底部,一种用于侧面。
网格组
- 在物体类中有一个组
(Group)
对象。使用.add()
方法将网格加入到组。用于同时操作网格组在场景中的坐标。
const group = new THREE.Group()
group.add(sphere)
group.add(cube)
scene.add(group)
- 在使用了组后。我们修改组的位置、缩放、旋转,是会同步到子对象的,他们被视为一个整体。当我们单独修改网格对象时,它的位置、缩放、旋转,都是相对于其父对象所在位置上进行变化。
- 我们通常说的,全局坐标就是场景的坐标,相对坐标是其父对象的坐标。
// 网格
const mesh = new THREE.Mesh(geometry, material)
// 相对坐标 x 移动5
mesh.position.x = 5
const mesh2 = new THREE.Mesh(geometry, material)
// 相对坐标 z 移动-10
mesh2.position.z = -10
const group = new THREE.Group()
group.add(mesh)
group.add(mesh2)
// 全局坐标x 移动10
group.position.x = 10
scene.add(group)
- 这里能清晰的看到子网格的位移都是在父坐标基础上改变的。