How to control opacity of an object with shaders?

I’m trying to make a simple box slightly transparent using shaders. like glass, But I can’t get it to work. I’m not sure what exactly I’m doing wrong?

	   var geometry = new THREE.BoxGeometry( 3, 6, 6 );//length,height,width

           var cubeShader = new THREE.ShaderMaterial({
            uniforms: {
                colorA: {type: 'vec3', value: new THREE.Color(0xffff00)},
                colorB: {type: 'vec3', value: new THREE.Color(0xffA500)}
            },
            vertexShader: vertexShader(),
            fragmentShader: fragmentShader()
          });
		cubeShader.opacity= 0.3;
		 cubeShader.transparent = true;
           var wall3 = new THREE.Mesh(geometry,cubeShader);
		   
		  
          wall3.castShadow=true;
           wall3.position.x+=30;
	  wall3.position.z+=7;
			
		  
           scene.add(wall3);





		
function fragmentShader() {
  return `
      uniform vec3 colorA; 
      uniform vec3 colorB; 
      varying vec3 vUv;

      void main() {
	 
        gl_FragColor = vec4(mix(colorA, colorB, vUv.z), 1.0);
      }
  `
}
function vertexShader() {
  return `
    varying vec3 vUv; 

    void main() {
      vUv = position; 

      vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
      gl_Position = projectionMatrix * modelViewPosition; 
    }
  `
}
		
           			//render 
             function render(){
               requestAnimationFrame(render);
			   fpcontrols.update(0.1);
              renderer.render( scene, camera );
            }
			
      

  
			render();

You’d need to take opacity into account in your fragment shader - it’s not applied automatically, your final gl_FragColor vec4 value should contain opacity as the 4th component.

2 Likes
function fragmentShader() {
  return `
      uniform vec3 colorA; 
      uniform vec3 colorB; 
      varying vec3 vUv;

      void main() {
	 
        gl_FragColor = vec4(mix(colorA, colorB, vUv.z), 0.5);
      }
  `
}

ong it was that easy… thank you

1 Like