How to hide a cube if z coordinate == 1

So I have the following code:

// Create Shape
var fixedCubeGeometry = new THREE.BoxGeometry( 1, 1, 1 );

  // Create a material, colour or image texture
  var fixedCubeMaterial = new THREE.MeshLambertMaterial( { 
      color: 0xE6F3F9,
      wireframe: false               
  } );

  // Positions of all fixed cubes
  var fixedCubeCoordinates = [
    { x:-3, y:3, z:1 }, 
    { x:-2, y:3, z:1 },  
    { x:-1, y:3, z:1 }, 
    { x: 0, y:3, z:1 },  
    { x: 1, y:3, z:1 },
    { x: 2, y:3, z:1 },
    { x: 3, y:3, z:1 },
      
    { x:-2, y:2, z:0 },  
    { x:-1, y:2, z:0 }, 
    { x: 0, y:2, z:0 },  
    { x: 1, y:2, z:0 },
    { x: 2, y:2, z:0 },   
  ];

  function createNewMeshObject(x, y, z) {
    var fixedCube = new THREE.Mesh( fixedCubeGeometry, fixedCubeMaterial );
    fixedCube.position.x = x;
    fixedCube.position.y = y;
    fixedCube.position.z = z;
    return fixedCube;
  }

  fixedCubeCoordinates.map( box => {
    scene.add(
      createNewMeshObject(box.x, box.y, box.z)
    );
  });

This part of the code works fine and renders the cubes perfectly. The thing is, I want to hide all the cubes where the z == 1

So I figured a simple if statement should do the trick. So I tried adding:

if ( fixedCube.position.z == 1){
transparent: true,
opacity: 0
}

But that didn’t work. I also tried:

if ( fixedCube.position.z == 1){
var fixedCubeMaterial = new THREE.MeshLambertMaterial( {
transparent: true,
opacity: 0
} );
}

Also didn’t do the job. So what am I missing here?

Thanks a lot

  function createNewMeshObject(x, y, z) {
    var fixedCube = new THREE.Mesh( fixedCubeGeometry, fixedCubeMaterial );
    fixedCube.position.x = x;
    fixedCube.position.y = y;
    fixedCube.position.z = z;
    fixedCube.visible = z == 1 ? !1 : !0;
    return fixedCube;
  }

https://threejs.org/docs/#api/en/core/Object3D.visible

OK this solution is way simpler then what I had in mind, thanks!

1 Like

I’m curious why you use !1 and !0 in your ternary which seems unnecessarily obtuse rather than standard false and true booleans which would read better?