Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js.

This script includes a sphere, a triangle, and a glTF object (car).

I activated a second layer: camera.layers.enable(1);

Assigned the sphere, triangle, and glTF object to layer 1:

car.layers.set( 1 );
sphere.layers.set( 1 );
triangle.layers.set( 1 );

However, when I set the camera to layer 1 (camera.layers.set(1)), the glTF object doesn't appear, while other elements do. It seems like I can't assign the glTF object to a different layer than the default layer.

Here is the code. What could be causing this issue?

Thank you for your help!

<script>

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(50, window.innerWidth/window.innerHeight, 0.1, 3000);
    camera.position.set( 0, 0.1, 1 );
    camera.layers.enable(1);
    camera.layers.set(1);


var renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setClearColor("#f5e5e5");
    renderer.setPixelRatio(window.devicePixelRatio);
    renderer.setSize(window.innerWidth, window.innerHeight);

    document.body.appendChild(renderer.domElement);



// LIGHT ------------------------------------------------------------------------------>

var dLight = new THREE.DirectionalLight( 0x0000ff, 6.5 );
    dLight.position.set(1500, -700, 500);
    dLight.castShadow = true;
    dLight.layers.set(1);
    scene.add( dLight);


// Load a glTF resource -------------------------------------------------------->

var loader = new THREE.GLTFLoader();
var car;
    loader.load('car.gltf', function ( gltf ) {
    car = gltf.scene.children[0];
    car.scale.set(0.5, 0.5, 0.5);
    car.position.z = 0;
    car.position.y = -0.095;
    car.layers.set(1);

    scene.add( gltf.scene );
    render();

    });



// SPHERE --------------------------------------------------------------->

var material = new THREE.MeshLambertMaterial();
var geometry = new THREE.SphereGeometry(0.05, 20, 20);
var sphere = new THREE.Mesh(geometry, material); 
    sphere.position.x = 0.25;
    scene.add(sphere);
    sphere.layers.set( 1 );



// TRIANGLE ------------------------------------------------------------->

var geometre = new THREE.Geometry();
    geometre.vertices.push(new THREE.Vector3(-0.25, -0.1, 0));
    geometre.vertices.push(new THREE.Vector3(0, 0.30, 0));
    geometre.vertices.push(new THREE.Vector3(0.25, -0.1, 0));
    geometre.vertices.push(new THREE.Vector3(-0.25, -0.1, 0));

var triangle= new THREE.Line(geometre, new THREE.LineBasicMaterial({ color: 0x000000, linewidth: 12 }));
    triangle.layers.set( 1 );
    scene.add(triangle);



// POST-PROCESSING  ------------------------------------------------------->

var composer = new THREE.EffectComposer(renderer);

var renderPass = new THREE.RenderPass(scene, camera);
    composer.addPass(renderPass);

var pass1 = new THREE.GlitchPass(0);
    composer.addPass(pass1);



// RENDER -------------------------------------------------------------->

    requestAnimationFrame(render);

    function render(){

    sphere.rotation.y += -0.02;
    car.rotation.y += 0.01;

    composer.render();

    requestAnimationFrame(render);

    };


</script>

Answer №1

To properly establish layers for all objects in the hierarchy, you must set them recursively like this:

gltf.scene.traverse( function( object ) {

    object.layers.set( 1 );

} );

It's important to note that by default, layer settings do not automatically cascade down to descendant nodes in the scene graph.

three.js r116

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 alter the color of options within a select tag when hovering the mouse over them

After searching through multiple websites, I couldn't find a solution on how to change the option background color on hover from blue to green. The screenshot provided below illustrates what I am requesting for in a clearer manner. https://i.sstatic. ...

jQuery slider - display unlimited images

Currently, I am encountering issues with a Flickity carousel of images. When an image/slide is clicked, a modal window opens to display a zoomed-in version of the image. The problem arises when there are more or fewer than 3 images in the slider — my cod ...

When utilizing React client-side rendered components, the state may fail to update while the script is actively running

I am currently facing an issue for which I don't have a reproducible example, but let me explain what I'm trying to do: class MyComponent extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

Thick labels in Chart.js are shortened with three dots

Is there a way to show the entire label without it getting truncated with 3 dots? I have experimented with different options from https://www.chartjs.org/docs/master/axes/index, including padding, but so far I haven't been successful. The full date da ...

Unable to retrieve field values from Firestore if they are numeric rather than strings

I need to display this information in a list format: li.setAttribute('data-id', updatesArgument.id);//'id' here unique id Example 1 name.textContent = updatesArgument.data().count;// Works if String Example 2 let i=1; nam ...

Enhance autocomplete functionality by adding an additional parameter specific to Zend Framework

My form includes two fields: country club The club field is generated using the ZendX_JQuery_Form_Element_AutoComplete Element, which also creates this javascript code: $("#club").autocomplete({"url":"\/mywebsite\/\/mycontroller\/au ...

Three.js - Attempting to apply a texture to a plane consistently results in a black rendering

I'm having trouble applying a texture to a plane. The image I'm using is 256x256, but it's rendering black instead of showing the texture. Can anyone point out where I might be making a mistake? //set up the floor var floorTexture = new TH ...

Using jQuery to locate and delete multiple attributes from div elements

My goal is to locate all div elements with the class name "comment-like" that also have data-id attributes set to 118603,1234,1234,118601,118597. If a div contains any of these data values, then I want to remove that data attribute. I've attempted th ...

Is it possible to configure npm install to install "bin" executables directly into the local node_modules directory (rather than the .bin directory)?

In my Node project, I am able to package it into a tarball using npm pack, and then install it in another directory for testing purposes. This allows the files specified in the "bin" section of my package.json file to be symlinked correctly into the node_m ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

"Redirecting visitors based on their location using GeoIP targeting for

Is there a way to implement a code that redirects users based on their location? For example, if a user accesses the site from the United Kingdom, they should be redirected to /UK/, if from the US to /US/, and if from anywhere in the EU (excluding the UK) ...

Encountering a "Unable to use import statement outside a module" issue when trying to import react-hook-mousetrap within a Next.js project

Currently experimenting with Next.js but encountering some challenges. Recently attempted to add react-hook-mousetrap and imported it as per usual: import useMousetrap from "react-hook-mousetrap"; However, this resulted in the following error: S ...

Discover the Power of Node.js with the @aws-sdk/client-s3 Package, Leveraging AWS CLI Credentials Stored in

A Nodejs project has been set up with media files stored in an S3 Bucket and utilizing the @aws-sdk/client-s3 as the AWS SDK Client. The project consists of two important files, namely .env and S3Bucket.js. The content of .env (located in the root directo ...

What are the benefits of using Bower.js when npm is already functioning well?

When working in the main project directory, running the command npm init will create a file called "package.json". If I need to install dependencies such as angular, jQuery and bootstrap, I can use the following commands: npm install angular --save-de ...

What is the best way to implement dynamic generation of Form::date() in Laravel 8?

Is there a way to dynamically generate the Form::date() based on the selection of 1? If 1 is selected, then display the Form::date() under the Form::select(). However, if 0 is selected, then hide the Form::date() in this particular view. For example: Sel ...

Maximizing code efficiency with jQuery toggleClass

After creating a code to validate input fields for empty values, I've come to realize that using jQuery toggleClass could potentially enhance or optimize it. However, I'm stuck on how to go about implementing this improvement. Any assistance woul ...

Issue encountered when trying to add data into MySQL database

Having trouble inserting data into my MySQL database, even though I believe I'm doing it correctly. Does anyone know how to troubleshoot this issue or if I may have overlooked something? Everything seems to be working fine, but for some reason, it&apo ...

Switch off any other currently open divs

I'm currently exploring a way to automatically close other div's when I expand one. Check out my code snippet below: $( document ).ready(function() { $( ".faq-question" ).click(function() { $(this).toggleClass('open'); $(this ...