复制网格
复制网格的两种主要方法是克隆它或创建它的实例。克隆为您提供了一个独立的网格副本,而实例仍然链接到其材质的原始副本。您无法更改网格实例的材质。网格章节中还提供了创建副本的高级方法。
克隆房子使用:
clonedHouse = house.clone("clonedHouse")
实例化使用:
instanceHouse = house.createInstance("instanceHouse")
在我们世界的这一点上,所有的房子都将使用与createInstance相同的材料。
在我们这样做之前,我们将建筑功能结合起来,分别制作宽度为 1 或 2 的房屋,独立式或半独立式房屋。
扩展房屋建筑功能:
const buildHouse = (width) => {
const box = buildBox(width);
const roof = buildRoof(width);
return BABYLON.Mesh.MergeMeshes([box, roof], true, false, null, false, true);
}
const buildBox = (width) => {
//texture
const boxMat = new BABYLON.StandardMaterial("boxMat");
if (width == 2) {
boxMat.diffuseTexture = new BABYLON.Texture("https://assets.babylonjs.com/environments/semihouse.png")
}
else {
boxMat.diffuseTexture = new BABYLON.Texture("https://assets.babylonjs.com/environments/cubehouse.png");
}
//options parameter to set different images on each side
const faceUV = [];
if (width == 2) {
faceUV[0] = new BABYLON.Vector4(0.6, 0.0, 1.0, 1.0); //rear face
faceUV[1] = new BABYLON.Vector4(0.0, 0.0, 0.4, 1.0); //front face
faceUV[2] = new BABYLON.Vector4(0.4, 0, 0.6, 1.0); //right side
faceUV[3] = new BABYLON.Vector4(0.4, 0, 0.6, 1.0); //left side
}
else {
faceUV[0] = new BABYLON.Vector4(0.5, 0.0, 0.75, 1.0); //rear face
faceUV[1] = new BABYLON.Vector4(0.0, 0.0, 0.25, 1.0); //front face
faceUV[2] = new BABYLON.Vector4(0.25, 0, 0.5, 1.0); //right side
faceUV[3] = new BABYLON.Vector4(0.75, 0, 1.0, 1.0); //left side
}
// top 4 and bottom 5 not seen so not set
/**** World Objects *****/
const box = BABYLON.MeshBuilder.CreateBox("box", {width: width, faceUV: faceUV, wrap: true});
box.material = boxMat;
box.position.y = 0.5;
return box;
}
const buildRoof = (width) => {
//texture
const roofMat = new BABYLON.StandardMaterial("roofMat");
roofMat.diffuseTexture = new BABYLON.Texture("https://assets.babylonjs.com/environments/roof.jpg");
const roof = BABYLON.MeshBuilder.CreateCylinder("roof", {diameter: 1.3, height: 1.2, tessellation: 3});
roof.material = roofMat;
roof.scaling.x = 0.75;
roof.scaling.y = width;
roof.rotation.z = Math.PI / 2;
roof.position.y = 1.22;
return roof;
}
我们现在扩大地面并稍微增加相机半径以适应多个房屋并能够查看它们。首先,我们为每种类型建造一所房子并放置它们。之后,我们将为剩余的房屋创建这些实例。在决定其他房屋的类型、位置和方向后,我们将使用循环来创建它们。
const houses = [];
for (let i = 0; i < places.length; i++) {
if (places[i][0] === 1) {
houses[i] = detached_house.createInstance("house" + i);
}
else {
houses[i] = semi_house.createInstance("house" + i);
}
houses[i].rotation.y = places[i][1];
houses[i].position.x = places[i][2];
houses[i].position.z = places[i][3];
}