Struggling to extract content from a loaded gltf scene in Three.js?

I am trying to change the opacity or transparency of the material in a gltf loaded model.

Despite looking at various examples, I am unable to locate any meshes. I have created this fiddle which indicates 'no mesh found'. Most examples I found follow the same method of obtaining the material by first ensuring it's a mesh and then accessing the material.

<style>
  canvas {
    display: block;
    width: 98%;
    height: 98%;
  }

</style>

<canvas id="canvasid"></canvas>

<script src="https://cdn.jsdelivr.net/npm/three@0.131.2/examples/js/controls/OrbitControls.js"></script>-->

<script async src="https://unpkg.com/twap/dist/es-module-shims.js"></script>
<script type="importmap">
  {
          "imports": {
            "three": "https://cdn.jsdelivr.net/npm/three@0.131.2/build/three.module.js"
          }
        }
    </script>

<script type="module">
  import * as THREE from 'three';
import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/twap/examples/jsm/loaders/GLTFLoader.js';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/twap/examples/jsm/controls/OrbitControls.js';

var scene = new THREE.Scene();
scene.background = new THREE.Color(0x6699cc);
const lights = [];
lights[0] = new THREE.PointLight(0xffffff, 1, 0);
lights[1] = new THREE.PointLight(0xffffff, 1, 0);
lights[2] = new THREE.PointLight(0xffffff, 1, 0);
lights[0].position.set(0, 100, 0);
lights[1].position.set(100, 100, 100);
lights[2].position.set(- 100, - 100, - 100);
scene.add(lights[0]);
scene.add(lights[1]);
scene.add(lights[2]);

const loader = new GLTFLoader();

loader.load("https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf", function (gltf) {
    const mesh = gltf.scene.children[0];
    scene.add(mesh);

    //I am having trouble with this code - it seems like everyone is able to check if it is a mesh and then access the material. Even after trying multiple models, I am unable to find any mesh. Assuming a material directly also doesn't work.
    gltf.scene.traverse((o) => {
        if (o.isMesh) {
            console.log("found mesh");
            console.log(o && o.material);
        } else {
            console.log("no mesh found");
        }
    });
}, undefined, function (error) {
    console.error(error);
});

var canvas = document.getElementById("canvasid");
var renderer = new THREE.WebGLRenderer({
    canvas: canvas,
    antialias: true
});
renderer.setSize(canvas.parentElement.clientWidth, canvas.parentElement.clientHeight);
var camera = new THREE.PerspectiveCamera(1, canvas.parentElement.clientWidth / canvas.parentElement.clientHeight, 1, 1000);
camera.position.z = 100;

const controls = new OrbitControls(camera, renderer.domElement);
controls.update();
controls.autoRotate = true;
controls.enableDamping = true;
var animate = function () {
    requestAnimationFrame(animate);
    controls.update();

    renderer.render(scene, camera);
};

window.addEventListener('resize', function () {
    renderer.setSize(canvas.parentElement.clientWidth, canvas.parentElement.clientHeight);

    camera.aspect = canvas.parentElement.clientWidth / canvas.parentElement.clientHeight;
    camera.updateProjectionMatrix();
}, false);

animate();

How can I locate and modify the mesh/material?

Answer №1

The traversal process is not effective because the first child of gltf.scene is added to scene. This alters the object hierarchy and disrupts the traversal.

To resolve this issue, simply reposition the following two lines of code after calling Object3D.traverse().

const mesh = gltf.scene.children[0];
scene.add(mesh);

It is recommended to consider that a glTF asset may contain more than just one child mesh:

scene.add(gltf.scene);

For the updated fiddle, visit: https://jsfiddle.net/ftcnby9e/

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

What is the method for individually extracting values from HTML using class li?

Is there a way to extract each value from the HTML within the li class separately? I have tried various methods but none have been successful. Can anyone provide a solution? Here is my JavaScript code: $(document).ready(function() { $(".list-grou ...

What is the name of the inherited class that invoked the function?

I am looking for a way to determine the name of the class of an object from within a function that called that function. My approach involves utilizing John Resig's class inheritance concept. For instance var CoreStuff = Class.extend({ log: function ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

A guide on transferring and transforming text data on the server

While I have a basic understanding of php, ajax, and javascript (including jQuery), I am still a beginner and could use some assistance with connecting the dots for this simple task: My goal is to allow the user to input text (for example: "I saw the sun, ...

The results from utilizing Mongoose's text search feature are inaccurate and not matching the expected

Currently, I am in the process of developing a recipe blog website using Mongoose, Node.js, and Express. However, I have encountered an issue with the text search functionality not producing the desired output. In my Recipe.js schema, I have included spec ...

A method for increasing a counter using only an instance of a class or function without accessing its methods or properties in Javascript

Looking at the task ahead, let increment = new Increment(); I have been tasked with creating a Javascript class or function called Increment in order to achieve the following: console.log(`${increment}`) // should output 1 console.log(`${increment}`); ...

Updating dropdown selection with ng-model in AngularJS

nameList includes [“Julia”, “Evan”, “Tomas”]; select ng-model=“names” ng-options=“x for x in nameList” In my controller, I make a service api call to GetNameByID/{id}” and based on the id, I need to set the default value of the drop ...

Poor performance of ParticleSystems in Three.js on weaker graphics cards

Currently, I am experimenting with particle systems to enhance the rendering speed of a star system, but I have encountered an issue with poor display quality on graphics cards with low capabilities, such as Intel HD which is quite common. The particles th ...

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

What could be causing the div to not respond to ngAnimate?

Recently, I encountered an issue with adding animations to a list of <div>'s in my webapp. After incorporating ngAnimate into the app.js file and including ng-animate="'animate'" in the <div>, I was disappointed to find that the ...

What is the best way to eliminate leading and trailing spaces from a text input?

I'm currently working on troubleshooting a bug in an AngularJS application that involves multiple forms for submitting data. One of the issues I encountered is that every text box in the forms is allowing and saving leading and trailing white spaces ...

Issue: .catch(error) function in Node / Express not returning as expectedDescription: After

I'm currently developing a REST API and focusing on effectively managing all error scenarios. Upon successful completion of the API call, I make sure to return the success object to the calling function and then send the response to the client. Howev ...

Debugging and ensuring the functionality of Cordova (Phonegap) HTTPS connections

There is an HTTPS site with an API that needs to be accessed. I need to work from Cordova (AngularJS) with its HTTPS API. Additionally, I want to debug the AngularJS app in a web browser (Chrome) because it's much quicker compared to rebuilding and ...

What steps should I take to resolve the error: Uncaught SyntaxError: expected expression, received '<'?

I'm facing an issue with my code. It works perfectly on my computer, but when I move it to the server, I encounter the following error. Error: Uncaught SyntaxError: expected expression, got '<' Here is the code snippet causing the prob ...

How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts: Let's consider the following routes I have set up: .when('/', { templateUrl : 'partials/homepage.html&ap ...

Combining React with Typescript allows for deep merging of nested defaultProps

As I work on a React and Typescript component, I find myself needing to set default props that include nested data objects. Below is a simplified version of the component in question: type Props = { someProp: string, user: { blocked: boole ...

Type-safe Immutable.js Records with TypeScript

I'm struggling to find a suitable solution for my query. I am aiming to define data types using an interface in TypeScript, but my data consists of Immutable.js records making it more complex. Please refer to the example provided below. interface tre ...

Non-reactive arrays in Vue.js

I am facing an issue. Here is the problem: data: { tracks: [] } The tracks array will contain a complex object. I want to achieve reactivity when assigning a new value to tracks nested object, but I do not need deep reactivity for the object. ...

using document references in puppeteer's evaluate/waitFor function

I'm feeling a bit lost when it comes to understanding the document reference in puppeteer's evaluate method. The official documentation shows some code that includes this reference within a waitFor function in a node script. I get that these line ...

When using Javascript, an error is being thrown when attempting to select a nested element, stating that it is not a function

I am facing a challenge in selecting an element within another element, specifically a button within a form. Typically, I would use jQuery to achieve this as shown below: element = $('#webform-client-form-1812 input[name="op"]'); However, due t ...