three.js 图层显示控制 layers_javascript

源码参照

three.js 图层显示控制 layers_图层_02


可以看到 只有物体的layer在相机的layers中three才渲染

实现
默认创建物体layer是0
如指定物体的layer为1不会渲染
需要渲染使用相机的​​​enable​​方法允许渲染

常用方法
​toggle​​方法 切换是否允许渲染状态
​enable​​方法 允许渲染某图层
​disableAll​​方法 关闭全部图层 - 黑屏
​disable​​方法 关闭指定图层

代码:

const box1Group = new THREE.Group();
const box2Group = new THREE.Group();
scene.add(box1Group, box2Group);

for (let i = 0; i < 10; i++) {
const box = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({ color: 0xffffff })
);
box.layers.set(1);
box.position.set(Math.random() * 4, Math.random() * 4, Math.random() * 4);
box1Group.add(box);
}

for (let i = 0; i < 10; i++) {
const box = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({ color: 0x5511ff })
);
box.layers.set(2);
box.position.set(Math.random() * 4, Math.random() * 4, Math.random() * 4);
box2Group.add(box);
}

gui.add(
{
toggle1Layers: () => {
// camera.layers.enable(1);
camera.layers.toggle(1);
},
},
"toggle1Layers"
);
gui.add(
{
toggle2Layers: () => {
camera.layers.toggle(2);
},
},
"toggle2Layers"
);

gui.add(
{
onlyShow1Layers: () => {
camera.layers.disableAll();
camera.layers.enable(0);
camera.layers.enable(1);
},
},
"onlyShow1Layers"
);
gui.add(
{
onlyShow2Layers: () => {
camera.layers.disableAll();
camera.layers.enable(0);
camera.layers.enable(2);
},
},
"onlyShow2Layers"
);