Utilize Three.js to render objects at the forefront by adjusting renderDepth

How can I render objects on top of other objects in a Three.js scene?

I am struggling to get the green torus knots to display above the red boxes and floor in my fiddle.

Despite trying various values like mesh.renderDepth = 0, 1, 1000, nothing seems to work.

The material I have created is:

material = new THREE.MeshBasicMaterial( { color: 0x00ff00, transparent: true, opacity: 0.5 } );

Is there any way to achieve this using renderDepth? Am I overlooking any other settings?

Setting depthTest to true does sort of work, but it's not ideal for concave meshes like the torus as they end up with overlapping polygons, especially when opaque.

Although I have not been successful in getting this alternative solution involving two scenes to function properly, it appears to be more complex and less versatile than just using renderDepth.

To see the issue in action, check out the fully operational JSFiddle: http://jsfiddle.net/QHssJ/

I appreciate any guidance or assistance you can provide. Thank you!

Answer №1

Although this post may be outdated, it's important to note that objects with a custom renderDepth should have their material configured with depthWrite set to false:

 material.depthWrite = false

For an updated version of the fiddle shared in the original post, visit: http://jsfiddle.net/QHssJ/20/

Answer №2

Behold a practical demonstration featuring the VisualLayers class designed for overseeing multiple layers effortlessly, employing the technique of setting renderer.autoClear = false along with clearing-depth method.

This strategy shines as it leaves the renderOrder of objects untouched (an alternative methodology) hence sidestepping any associated issues with renderOrder.

Feel free to experiment with the user interface options to observe its effects:

// @ts-check

////////////////////////
// LAYER SYSTEM
////////////////////////

/** @typedef {{name: string, backingScene: THREE.Scene, order: number}} Layer */

class VisualLayers {
    /**
     * @type {Array<Layer>}
     * @private
     */
    __layers = [];

    constructor(
        /** @private @type {THREE.WebGLRenderer} */ __renderer,
        /** @private @type {typeof THREE.Scene} */ __Scene = THREE.Scene
    ) {
        this.__renderer = __renderer;
        this.__Scene = __Scene;
    }

    defineLayer(/** @type {string} */ name, /** @type {number=} */ order = 0) {
        const layer = this.__getLayer(name);

        // The default layer always has order 0.
        const previousOrder = layer.order;
        layer.order = name === "default" ? 0 : order;

        // Sort only if order changed.
        if (previousOrder !== layer.order)
            this.__layers.sort((a, b) => a.order - b.order);

...

(window.onresize = function (event) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
})();

...

html,
body,
#container {
    margin: 0px;
    padding: 0px;
    width: 100%;
    height: 100%;
}

canvas {
    background: transparent;
    display: block;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
}
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed999a888c869d8c8388addcc3d8c3d8">[email protected]</a>/dist/tweakpane.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/stats.js/r11/Stats.min.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f98d918b9c9cb9c9d7c8cbc8d7c8">[email protected]</a>/build/three.min.js"></script>
<script src="//unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b4b54484f4b4954585e484852555c7b0d150a0c150f">[email protected]</a>/build/postprocessing.js"></script>

(view example on codepen)

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

Is there a way to retrieve real-time information from an API by utilizing the HTTP.Get method?

When working with ANGULAR I am faced with the challenge of pulling data from an API using http.get at regular intervals. The API continuously updates minute by minute traffic data, and I need Angular to display these live updates. Currently, my approach ...

Arranging rows according to an array value containing column (PHP/MySQL/jQuery)

Initially, I am seeking a solution using PHP/MySQL and JS/jQuery, but I am unsure of the most effective approach for handling larger datasets (40,000+). Consider a scenario where you have a database and wish to enable sorting of a table based on a column ...

Having trouble properly sending gender value through javascript/ajax functionality

Within my database, the gender_id attribute is configured as an enum with options ('M', 'F') and M serves as the default selection. Gender Selection Form <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <label>Gend ...

What is the best way to specify the stream responseType for my client?

Is there a way to download a file from my express js app using AJAX instead of server-side handling? const response = await Axios({ method: 'GET', url: url, responseType: 'stream' }) Instead of piping the data directly to ...

`Cannot press when using custom cursor in JS?`

Hey there! I'm currently working on implementing a custom cursor for specific elements on my website. However, I've encountered a little hiccup - once the custom cursor is in place, I'm no longer able to click on any elements. Does anyone ha ...

Replace Jade script with block override

Having trouble overriding a Jade script. tag, nothing seems to work. Here is the code snippet: Layout.jade block foot footer.container#footer .row .twelve.columns All rights reserved. &copy; 2015 Pet Feeder block scripts ...

The problem with legends in chart.js not displaying properly

I've been struggling to display the labels "2017" and "2018" as legends on the right side of the chart. I've tried numerous approaches but haven't found a solution yet. The purpose of showing these legends is to easily identify that each co ...

Ways to retrieve session variables within a PHP code?

I'm working on a notifications feature and encountering an issue with my jQuery function calling the "NOTIFICACIONES.php" script using AJAX. The PHP script is supposed to fetch data from the database using the current user's ID, but in the ajax s ...

Is it possible to use the POST method with NODE JS and JavaScript?

Struggling to set up a login screen, I keep running into a "cannot get post" error after hours of trying everything. Feeling defeated, I decided to seek help. Here's the code I have so far: const express = require('express'); const router = ...

Customize the CSS for the column containers in Material-UI's DataGrid with the

I am facing a challenge in trying to override the CSS property position on the .MuiDataGrid-columnsContainer. Upon reviewing the information available on https://material-ui.com/api/data-grid/#css, it seems that there is a rule defined for root but not spe ...

Can the variable name within a function be retrieved?

How can I retrieve the variable name (user_name1 or user_name2) from a sample function (GetUserName()) within itself? This variable name is required to create an object with the same name on the server side for data synchronization purposes. function GetU ...

The Ajax query returned a successful response, yet it unexpectedly triggered an error

Currently, I am delving into the realm of mongodb. I have integrated Express, Body-Parser, and Mongoose into my project, and I'm retrieving data from an online mongodb database hosted on mlab. Everything seems to be functioning smoothly as I've t ...

Utilizing Subdirectories in a Command Manager

My goal is to organize my commands into sub folders, but for some reason my bot is not recognizing the commands inside those folders. Strangely, no error message is being displayed. const fs = require('node:fs'); const Discord = require('dis ...

Using Firebase to connect and disconnect from state in React with Re-base

I'm encountering some issues with React and Firebase while using the re-base module. When attempting to retrieve content from Firebase across different components in my app, I run into a problem. On one component/"page," which is home, I have the abi ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

Display/conceal within a jQuery fixed navigation bar (center-aligned)

I am facing challenges with creating a sticky menu that shows/hides with a click button. Considering abandoning the show/hide feature altogether and rebuilding it from scratch in the future. Two major problems I have identified: How can I make the sho ...

Trouble displaying JSON data when using a search box filter in React

My webpage is using JSON dummy data that can be filtered by keywords entered into a search box. Previously, all the data displayed correctly before creating filteredJson, but now nothing is showing up. What could be causing this issue? I want to send the ...

What is the functioning of the node.js next() middleware without any parameters supplied?

When working with middleware functions in Express, the signature typically includes function (req, res, next). However, it may be surprising to some that the next() call does not require any arguments. This concept can be better understood by considering t ...

Is it possible to determine if a style property has been altered

I am looking to identify changes in CSS properties without needing the actual values. I only require the specific style property that has been altered. For example, I need the style property to be stored in a variable, as shown below: document.getElementB ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...