In my current project using three.js, I am working on a 2D game where I need to render background scenery followed by a transparent quad that still writes values to the depth buffer even though it has an opacity of zero. The challenge arises when trying to render objects behind this quad with specific z-values to ensure that fragments at the same screen space position as the transparent quad are discarded due to failing the depth test.
Despite my knowledge of OpenGL suggesting this is feasible, I have encountered issues in implementing this concept in three.js. It seems that depth values are not being written for the transparent quad when the fragment shader output results in gl_FragColor.a === 0
.
I have disabled object sorting with renderer.sortObjects = false
and set the background at z = 0
, the transparent quad at z = 1
, and the masked objects at z = 0.5
.
For the transparent quad, I have tried setting material.transparent = false
but instead of displaying the background scenery over the quad, it shows the clear color.
The code snippet below demonstrates how I create the transparent quad:
// JavaScript code snippet for creating transparent quad using ShaderMaterial
let uniforms = {
// Uniform variables definition here
}
let vertex_shader =
`// Vertex shader code here`
let fragment_shader =
`// Fragment shader code here`
// Geometry setup
let geometry = new three.PlaneGeometry(1, 1)
geometry.scale(1, -1, 1)
// Material setup
let material = new three.ShaderMaterial({
uniforms,
vertexShader: vertex_shader,
fragmentShader: fragment_shader,
transparent: true,
})
let mesh = new three.Mesh(geometry, material)
mesh.position.set(0.5, 0.5, 0)
let root = new three.Object3D()
root.add(mesh)