Toggling visibility of a GLTF doesn't update in viewport, using Three.js & React

54 Views Asked by At

I need to toggle the visibility of models based on button clicks, yet all of my attempts have the same problem: the visible properties will change when set them, but the view port doesn't reflect the changes. Posted relevant code below.

  let ceramicObj = new THREE.Object3D();

  const testClick = () =>{
    console.log('click')
    console.log(ceramicObj)
    ceramicObj.visible = !ceramicObj.visible;
  }

  useEffect(() => {
    loader.load(`/Models/ceramic.gltf`, (gltfScene) => {

      let ceramic = gltfScene.scene;
      ceramicObj.add(ceramic)
      console.log('loaded 1')
      scene.add(ceramic);
    })

    loader.load(`/Models/rubber.gltf`, (gltfScene) => {

      let rubber = gltfScene.scene;
      rubber.rotation.y = 3.14159;
      console.log('loaded 2')
      scene.add(rubber);
    })

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize( mountRef.current.offsetWidth, mountRef.current.offsetHeight );
    mountRef.current.appendChild( renderer.domElement );
    renderer.shadowMap.enabled = true;

    const camera = new THREE.PerspectiveCamera( 75, mountRef.current.offsetWidth / mountRef.current.offsetHeight, 0.01, 1000 );
    const controls = new OrbitControls( camera, renderer.domElement );

    const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    
    const light = new THREE.PointLight(0xffffff, 100)
    const ambLight = new THREE.AmbientLight( 0xffffff, 0.25 );
    
    scene.add( light );
    scene.add( directionalLight );
    scene.add( ambLight );
  
    camera.position.y = 1.4;
    camera.rotation.x = -1.5708;

    light.position.set(0,5,5);

    scene.background = new THREE.Color("rgb(245, 245, 245)");
    
    function animate() {
      requestAnimationFrame( animate );
      renderer.render( scene, camera );
    }

    let onWindowResize = function () {
      camera.aspect = mountRef.current.offsetWidth / mountRef.current.offsetHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(mountRef.current.offsetWidth, window.innerHeight - 64);
    }

    window.addEventListener("resize", onWindowResize, false);

    animate();
    
    return () => mountRef.current.removeChild(renderer.domElement);
  }, [])

I have tried moving the visibility change to adding the visibile = false/true code to useEffect, button click functions, and using states to change the value. The only thing that responds is setting it in the load function which doesn't help me as it only runs the initial time.

0

There are 0 best solutions below