Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click?

I am loading an external .obj file:

loader.load( obj, function ( object ) {

    createScene( object, mod.tipo, pid, cor.replace("#","0x") );

});

and adding it to a group

function createScene( geometry, name, id, cor ) {

    geometry.traverse( function ( child ) {

        if ( child instanceof THREE.Mesh ) {

            var material = new THREE.MeshPhongMaterial( {
                specular: 0xffffff,
                shininess: 10,
                side: THREE.DoubleSide,
                map: THREE.ImageUtils.loadTexture('/3d/js/texturas/white.jpg'),
                shading: THREE.SmoothShading
            } );

            material.color.setHex(cor);

            child.material = material;

            group.add( child );     

        }

Then this group is added to the scene: scene.add( group )

To hide the mesh, I set its visibility to false. However, I want to completely remove it from both the scene and the group.

I have already tried using scene.remove('name') or scene.remove(mesh), but they did not work. Does anyone know how to achieve this?

Answer №1

If you're looking to accomplish this task, consider implementing the following code:

const targetNode = scene.findNodeByAttribute('name', true);
if (targetNode !== null) {
    scene.remove(targetNode);
}

This piece of code will identify a node with the name 'name' in your scene and promptly remove it from the scene.

Answer №2

After much trial and error, I finally found a solution:

In my specific situation, I had grouped meshes together in order to rotate them all to the starting position.

Initially, I attempted to add the meshes directly to the scene, but encountered problems when trying to manipulate them as a group. This led me to rethink my approach and work with a global variable containing an array of all meshes instead.

This is the function that proved to be successful:

var clearScene = function(name) { var objsToRemove = scene.children;

for (var t = 0; t<objsToRemove.length; t++){

    if (objsToRemove[t] instanceof THREE.Mesh) {

      if (objsToRemove[t].name = name) {
        scene.remove(objsToRemove[t]);
        break;
      }

    }

}

}

By iterating through each mesh element, I was able to pinpoint the one I wanted to remove from the scene simply by calling the 'remove' method.

This approach worked for me.

I realized the need to revise my grouping strategy and possibly adjust how I rotate meshes individually to their default positions, which could potentially improve performance.

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

Obtaining the data stored in objects within a parse database

I'm currently facing an issue where I am trying to retrieve the name of the creator from the session object, which is a pointer. For testing purposes, I have been attempting to access this information but it keeps showing up as undefined. Any suggesti ...

The error message "Express Routing - Attempting to access property 'include' of undefined" is displayed when an

I am attempting to implement basic routing based on the user's selections on the first page. If the user picks 2 out of 3 options on the parent page, I want them to only see those two child pages and not the third. My strategy for the parent page was ...

Ramda Transitioning to a Liberated Style of Programming

Unable to find a suitable resource for this particular issue. I apologize if this question has already been asked, but my attempts to locate the answer have proven fruitless (perhaps due to a lack of effective search methods). I've developed a functi ...

Mastering the art of crafting form elements with jQuery

My code is looking like this: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function afterText() { var textElement = document.create ...

What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass. if ($('.sidebar-menu-container li').hasClass('current-menu-item')) { $(this).addClass('expanded'); } Check out this CodePen for reference. ...

What is the best way to retrieve data input from my select dropdown?

I have a select menu generated from a database and I want to display the value of the selected option in an input field. Currently, my code only shows the value of the first option. How can I modify it to display all selected values? Thank you. <?php ...

Issues encountered when trying to implement helperText in mui date picker

Can someone assist with this issue? The helper text is not displaying as expected in the following code snippet: <div className={classes.container}> <LocalizationProvider dateAdapter={AdapterDateFns}> <Des ...

Incorporate titles for items in the jquery caroufredsel plugin

I am currently using the second example of the caroufredsel plugin, which can be found on this page . I am attempting to add a caption for each picture. To achieve this, I have used `li` and `lis` in my HTML code: <div class="list_carousel"> &l ...

Retrieve data from an external website containing an HTML table without a table ID using Java Script and transform it into JSON

I have developed a script that can convert HTML table data into a JSON Object. To accomplish this task, I utilized the jquery plugin created by lightswitch05. With this code, I am able to extract data from an HTML table on the same web page using: var t ...

Encountering an error with Gatsby while running the development environment due to issues with antd and less configuration (NPM

Encountering issues with the development server in local after installing antd, less, less-loader, gatsby-plugin-less, and gatsby-plugin-antd Versions: "gatsby-plugin-less": "^6.20.0", "less": "^2.7.1", "less- ...

Using Javascript to emphasize Ajax Response

I am faced with a challenge of highlighting specific words within text received from an ajax response, before generating HTML code and inserting it into the DOM. At the moment, I am utilizing the following code snippet: function highlightWords(line, word, ...

What is the command to invoke an asynchronous method from the node console?

I am working on a Bot class with an async printInfo method: class TradeBot { async printInfo() { //..... } } When I start 'node', and create an object from the console to call the method: >const createBot = require('./BotFactory&ap ...

Sending JSON data containing an IFormFile and a string as parameters to C#

Software Versions: ASP.NET and Web Tools - 17.10.341.11210 C# Tools - 4.10.0-3.24312.19+ JQuery - 3.3.1.js JS - 2.8.3.js Currently, I am attempting to pass an IFormFile and a string from a JSON file select and a string input. After thorough testing, I ha ...

Can security groups be dynamically updated using a JSON file in JavaScript rather than relying on manual parameters?

Looking to enhance security group rules, I aim to have my javascript file extract data from a separate json file instead of relying on json parameters directly. After initially using json parameters for security group updates, I am now exploring the metho ...

AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem: The function has a complexity of 11 ...

Identify and handle multiple scenarios in JavaScript without using if statements

I have developed a function that is supposed to evaluate all scenarios and provide an immediate result if one of the cases does not match. const addText = (data, addAlternative) => { return (data !== 'N/T' || data === 0 || data) ? d ...

Can you explain the concept of F-Bounded Polymorphism in TypeScript?

Version 1.8 of TypeScript caught my attention because it now supports F-Bounded Polymorphism. Can you help me understand what this feature is in simple terms and how it can be beneficial? I assume that its early inclusion signifies its significance. ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

"Modify hyperlink attributes to enhance security and optimize user experience

$("a[href*='youtube']").attr('rel', 'prettyPhoto'); Having some trouble targeting links on a page containing "youtube" in the URL. I'm trying to set their rel attribute to "prettyPhoto" so they open in a lightbox window. ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...