BabylonJS - 网格实例
如果您想在场景中绘制相同的网格,请使用实例。
语法
var newInstance = mesh.createInstance("i" + index); // 创建新实例
演示
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>BabylonJs - Basic Element-Creating Scene</title>
<script src = "babylon.js"></script>
<style>
canvas {width: 100%; height: 100%;}
</style>
</head>
<body>
<canvas id = "renderCanvas"></canvas>
<script type = "text/javascript">
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var createScene = function() {
var scene = new BABYLON.Scene(engine);
scene.clearColor = BABYLON.Color3.Gray();
// 这将创建并定位一个自由相机(非网格)
var camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);
// 这将相机定位到场景原点
camera.setTarget(BABYLON.Vector3.Zero());
// 这将相机附加到画布
camera.attachControl(canvas, true);
var light = new BABYLON.DirectionalLight("dir01", new BABYLON.Vector3(0, -1, -0.3), scene);
light.position = new BABYLON.Vector3(20, 60, 30);
// 地面
var ground = BABYLON.Mesh.CreateGround("ground1", 50, 50, 2, scene);
ground.receiveShadows = true;
var array_instances = [];
// 树木
BABYLON.SceneLoader.ImportMesh("", "scenes/", "Rabbit.babylon", scene, function (newMeshes,articleSystems,skeletons) {
var rabbit = newMeshes[1];
rabbit.isVisible = false;
var range = 50;
var count = 100;
for (var index = 0; index < count; index++) {
var newInstance = rabbit.createInstance("i" + index);
var x = range / 2 - Math.random() * range;
var z = range / 2 - Math.random() * range;
newInstance.position = new BABYLON.Vector3(x, 0, z);
newInstance.scaling = new BABYLON.Vector3(0.05, 0.05, 0.05);
array_instances.push(newInstance);
}
});
return scene;
};
var scene = createScene();
engine.runRenderLoop(function() {
scene.render();
});
</script>
</body>
</html>
在上面的演示链接中,我们使用了 Rabbit.babylon 网格。您可以从此处下载 Rabbit.babylon 的 json 文件
将文件保存在场景中以获取下面显示的输出。
输出
上面的代码行将生成以下输出 −
说明
以下代码有助于在场景中创建相同的网格 −
var array_instances = [];
// Trees
BABYLON.SceneLoader.ImportMesh("", "scenes/", "Rabbit.babylon", scene, function (newMeshes, particleSystems, skeletons) {
var rabbit = newMeshes[1];
rabbit.isVisible = false;
var range = 50;
var count = 100;
for (var index = 0; index < count; index++) {
var newInstance = rabbit.createInstance("i" + index); // 创建新实例
var x = range / 2 - Math.random() * range;
var z = range / 2 - Math.random() * range;
newInstance.position = new BABYLON.Vector3(x, 0, z); // 设置所创建实例的位置。
newInstance.scaling = new BABYLON.Vector3(0.05, 0.05, 0.05);//在 x、y 和 z 轴上缩放实例。
array_instances.push(newInstance);
}
});
return scene;

