项目需求:自己根据货架长宽高绘制货架,只提供货架的横梁和立柱模型(fbx)
下图是生成的货架 货架.png解决方法:
1、将引入的模型先用group合并
主要代码,大部分代码都可以忽略,主要看调用meshMerge方法的入参是什么
// 添加货架
initShelf() {
const fbxLoader = new FBXLoader();
const textureLoader = new THREE.TextureLoader();
const beam_group = new THREE.Group(); // 横梁组
const upright_group = new THREE.Group(); // 立柱组
// 获取横梁&立柱
fbxLoader.load(`./static/fbx/models/立库-横梁-01.FBX`, (fbx) => {
const mesh = fbx.clone();
// 添加贴图材质
const material = new THREE.MeshPhongMaterial({
map: textureLoader.load(
"./static/fbx/textures/组件-轨道立库-8192-01.jpg"
),
});
mesh.traverse((child) => {
// 横梁
if (child.isMesh && child.name == "ZJ-05") {
// 添加贴图材质
child.material = material;
child.rotateZ(-Math.PI / 2);
this.shelf.forEach((item) => {
const group = new THREE.Group();
const positions = this.computerBeamPosition(item);
positions.forEach((v) => {
const beam = child.clone();
beam.rotateX(v.rotation); // 设置旋转角度
beam.scale.set(
0.001,
0.001 * Math.abs(item.startPosition.x - item.endPosition.x),
0.001
);
beam.position.set(v.x, v.y, v.z);
group.add(beam);
});
// beam_group.add(group); // 这是没合并前的代码
// 合并当前横梁
const mergeMesh = this.meshMerge(group, item.name);
beam_group.add(mergeMesh);
});
}
// 立柱
if (child.isMesh && child.name == "LKZJ-01") {
child.material = material;
this.shelf.forEach((item) => {
const group = new THREE.Group();
const positions = this.computerUprightPosition(item);
positions.forEach((v) => {
const upright = child.clone();
upright.scale.set(0.001, 0.001, 0.002 * item.uprightHeight); // 设置立柱高度(+0.001突出来半截)
upright.rotateZ(v.rotation); // 设置旋转角度
upright.position.set(v.x, v.y + item.uprightHeight / 2, v.z); // 高度抬高到立柱一半
group.add(upright);
});
// upright_group.add(group); // 这是没合并前的代码
// 合并当前立柱
const mergeMesh = this.meshMerge(group, item.name);
upright_group.add(mergeMesh);
});
}
});
scene.add(beam_group);
scene.add(upright_group);
});
},
2、将group用BufferGeometryUtils.mergeBufferGeometries 合并
主要代码
meshMerge(object, name) {
const geometries = [];
const materialArr = [];
object.traverse((obj) => {
const child = obj;
if (child.isMesh) {
const geo = child.geometry.clone();
if (Array.isArray(child.material)) {
child.material = child.material[0];
}
materialArr.push(child.material);
geo.index = null;
child.updateWorldMatrix(true, true);
geo.applyMatrix4(child.matrixWorld);
geometries.push(geo);
}
});
// console.log(geometries);
const buffergeo = BufferGeometryUtils.mergeBufferGeometries(
geometries,
true
);
// console.log(buffergeo);
const mesh = new THREE.Mesh(buffergeo, materialArr);
name && (mesh.name = name);
return mesh;
},
网友评论