What is the process for obscuring items using the depth buffer in three.js?

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)

Answer №1

As of version r73, the key to success lies in meticulous control over the renderOrder and position properties of your three.Mesh.

To start, I reinstated object sorting by removing the line renderer.sortObjects = false. Next, I made sure that the masked objects were positioned behind the transparent quad by adjusting their z coordinates.

Lastly, I assigned a renderOrder value of 1 to each three.Mesh object that needed to be masked (meaning they would render after any mesh with a renderOrder less than 1), and set a value of 0.5 for the transparent quad. If no renderOrder was specified, the default value of 0 was used, rendering those meshes before the transparent quad and masked objects.

Remember, the renderOrder property must be set individually per mesh and does not affect child Object3D objects.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular Pagination: An issue arises when deleting records from the first page, as the following page's records are not automatically refilling the first page

I have implemented angular pagination to display records. Each record has a button labeled 'Assign to me'. Clicking on this button removes the selected record from the list. However, I am facing an issue where I display 10 records per page and if ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

Can the server-side manipulate the browser's address bar?

Picture this scenario: a public display showcasing a browser viewing a web page. Can you send a GET or POST request from a mobile device to an HTTP server, causing an AJAX/pubsub/websocket JavaScript function to alter the displayed page on the screen? Per ...

Removing data using axios in a React project

I'm currently working on a small app using the Json server package to help me keep track of movies I want to watch in my free time. I am looking to learn React and Axios, so I decided to build this app with these technologies. The concept is simple - ...

Activate Click, or Pop-up Box

I've been attempting to log in to the Udemy site using JavaScript, but I'm having trouble triggering the click action on the "log in" link. Unfortunately, the .click() method doesn't seem to be working when I try to select the element. The l ...

Don't pay attention to jquery.change

Consider the code snippet below: $(".someSelector").change(function() { // Do something // Call function // console.log('test') }); An issue arises where this code is triggered twice: once when focus is lo ...

Ways to remove the uploaded document

I have been tasked with uploading a file. The file comes with a remove button, which can be pressed to delete it. Below is the code I used: The code snippet is as follows: <div id="main"> <p id="addfile1">Add File</p> <div id ...

React: Assigning a unique className to an element in a list

In the code snippet below, I am attempting to add a className based on the state of the checkbox. While the className is being added correctly, the issue arises when it gets applied to all elements in the list upon checking/unchecking any checkbox. I aim ...

Encountered an issue with Nextjs dynamic routes and static pages where the error message states that the `paths` variable needs to be an

I have been following the official Next.js guide on generating statically generated pages with dynamic routes (Nextjs - Dynamic Routes). However, I am facing an issue when trying to generate pages with fetched data. The error message I am receiving is as f ...

When multiple checkboxes are selected, the corresponding form fields will be automatically filled with shared information

When the user checks multiple checkboxes, corresponding form fields should appear based on the checkboxes selected. For example, if the user checks both the flight and hotel checkboxes, the fields for full name and last name should be displayed, while othe ...

Transforming a numeric value into a 4-byte array using JavaScript

Attempting to write a node server has brought me to the challenge of sending a 32-bit integer to a C# client as the header. The bit shift operators are a bit confusing for me and I am uncertain about how to proceed. It seems that my C# client expects thes ...

What is the method for obtaining a date in the format of 2018-05-23T23:00:00.000+00:00?

Recently, I've been attempting to filter data based on dates in my database. The format in which the dates are saved is as follows: 2018-05-23T23:00:00.000+00:00 This was my initial approach: router.get('/byDate', function (req, res) { ...

"What are some strategies for locating a specific item within a MongoDB database, or perhaps querying for all

I am currently searching for a specific item using the following code: Product.find({ category: "bracelet" }); In one scenario, I need to find items with any category value or simply search for all items like this: let cat; if (req.body.cat) ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

Error: The 'document' object is not recognized in this context (React)

I attempted to display my main page using routes but I am still encountering the same ReferenceError. Below is my code snippet: import React from "react"; import ReactDOM from "react-dom/client"; import App from "../components/app ...

Exploring the Depths of Angular Reactive Forms with Recursion

Dealing with recursion and form groups app-root.component.html <div [formGroup]="form"> some content <app-root></app-root> </div> Is it possible to implement the same form group and form controls in my recursive structure? For ex ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

"Permission denied to access restricted URI" error encountered while attempting to utilize ng-template functionality

I am attempting to implement ng-include for recursive templates in my HTML. After testing it on jsfiddle and confirming that it works, I tried the same locally. However, I encountered the following error: Error: Access to restricted URI denied createHttpB ...

Storing a class method in a variable: A guide for JavaScript developers

I am currently working with a mysql connection object called db. db comes equipped with a useful method called query which can be used to execute sql statements For example: db.query('SELECT * FROM user',[], callback) To prevent having to type ...

Updating the div#content dynamically with Jquery without the need to refresh the page

After spending countless hours on this forum, I have yet to find a solution that perfectly fits my needs, so I will pose my question. Here is the gist of what I am attempting to accomplish: When the page loads, the default page fades in and displays. Wh ...