Is there a way to manipulate each object that I create in Three.js?

Currently, I am working on developing a scene with three.js and incorporating 3 spheres into it. My goal is to switch all wireframe materials of the spheres created to non-wireframe ones. I opted not to use scene.traverse() as my scene contains multiple objects and I only wish to modify the spheres. However, with my existing code, I am limited to switching only one sphere. How can I access each individual sphere? Any assistance would be greatly appreciated. Thank you!

var numSpheres = 3;

function createSphere (x, y, z){

    sphere = new THREE.Object3D();

    material = new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true});
    geometry = new THREE.SphereGeometry (2, 8, 8);
    mesh = new THREE.Mesh(geometry, material);

    sphere.add(mesh);
    sphere.position.set(x, y, z);

    scene.add(sphere);
}

createSpheres(numSpheres){

    for(i = 1; i <= numSpheres; i++){       
        var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
        var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;

        createSphere(randomnumber1, 3, randomnumber2);
    }
}
function onKeyDown(e){

    case 65: 
    case 97:
        sphere.traverse(function (node){
                if(node instanceof THREE.mesh) {
                    node.material.wireframe = !node.material.wireframe;
                }
        });

Answer №1

Following @prisoner849's advice, organize the objects you wish to modify in either an array or map. By doing so, you can avoid using instanceof THREE.Mesh and solely focus on manipulating the intended objects.

const numSpheres = 3;
let spheresMap = {}; // OR
let spheresArray = [];

function createSphere(x, y, z){

    const sphere = new THREE.Object3D();

    material = new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true});
    geometry = new THREE.SphereGeometry (2, 8, 8);
    mesh = new THREE.Mesh(geometry, material);

    sphere.add(mesh);
    sphere.position.set(x, y, z);

    scene.add(sphere);

    spheresMap[sphere.id] = sphere; // OR
    spheresArray.push(sphere);
}

createSpheres(numSpheres){

    for(let i = 1; i <= numSpheres; i++){       
        let randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
        let randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;

        createSphere(randomnumber1, 3, randomnumber2);
    }
}
function onKeyDown(e){

    switch (e.key) {
      case 'a': 
      case 'A':
        for (let key in spheresMap) {
            spheresMap[key].material.wireframe = !spheresMap[key].material.wireframe;
        }
        // OR
        for (let i=0; i<spheresArray.length; i++) {
            spheresArray[i].material.wireframe = !spheresArray[i].material.wireframe;
        }
    }
}

Answer №2

In the future, if you are able to access your spheres individually, the most important aspect is organizing them in an array within an object:

 function createSphere (x, y, z){

        var sphere= new THREE.Mesh(new THREE.SphereGeometry (2, 8, 8), new THREE.MeshBasicMaterial({ color: 0XFFA500, wireframe: true}));

        scene.add(sphere);
        sphere.position.set(x, y, z);    
        return sphere;

 }

 mySpheres = {};
 mySpheres.models = [];
 mySpheres.materials = [];

 for(i = 1; i <= 3; i++){       
        var randomnumber1 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;
        var randomnumber2 = Math.floor(Math.random() * (29.5 - -29.5 + 1)) + -29.5;

        var obj = createSphere(randomnumber1, 3, randomnumber2); // 
        var id = obj.id; // or whartever (redone,barrack,donald,george)
        mySpheres.models[id] = obj;
        mySpheres.materials.push(obj.material);
 }


    //after that you can do 
    mySpheres.models['donald'].translateX(10); 
    //or 
    mySpheres.models['george'].material.opacity = 0.5;
    //or
    mySpheres.materials.forEach(function(m) {
         m.opacity = 0.5;
    });

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 process for accessing the theme spacing unit in MUI 5?

In previous iterations of MUI, accessing the theme spacing unit was possible through theme.spacing.unit, with a default output of 8. However, this property has been removed in MUI 5. I am having trouble finding documentation on how to access the theme sp ...

Using JavaScript to Transmit URL

Imagine I have a URL similar to this: http://localhost:8000/intranet/users/view?user_id=8823 All I aim to achieve is to extract the value from the URL using JavaScript, specifically the user_id (which is 8823 in this instance), and transmit it through an ...

Issue with decompressing the identical data using zlib (Z_BUF_ERROR)

Below is the Python code snippet I am working with: import zlib raw = bytes.fromhex("789C34C9410AC2301005D0BBFC752289A88BB94A53CAD8061B48D3329D2A1A7277DDB87BF02A14548E9C0DF63FD60DE49DC104AA98238BDE23EB908A467972065DFCF9FAFB4185C708EAD0053C58E38BDF769 ...

Using v-model with the Toast-UI editor in Vue.js adds a dynamic and

Is there a way to bind the input value while using toast-ui vue-editor since it doesn't support v-model? Here is my setup for toast-ui: import '@toast-ui/editor/dist/toastui-editor.css'; import { Editor } from '@toast-ui/vue-editor&apos ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

Any suggestions for resolving issues with tipsy, SVG, and CSS on Firefox?

Having difficulty getting tipsy tooltips to display correctly next to the cursor in Firefox for my svg elements generated with d3. I discovered a patch that resolves most of the issues, which I found through this helpful answer about Tipsy tooltip position ...

Restrict the size of AJAX response

As I work on my decentralized application where I only have control over the client and not the servers, I am looking to implement measures to prevent malicious activities. One of the important considerations is preventing DoS attacks on the client through ...

"Encountering issues with ModalPopupExtender in Internet Explorer, while it functions properly in

Currently, I am encountering a critical issue while implementing ajaxmodalpopupextender on my webpage. The functionality operates smoothly in Firefox with an appealing appearance, however, it encounters display problems in IE where it appears to the side a ...

Having trouble with npm and unable to find a solution that works. Any suggestions on how to fix it?

I've been working on a JavaScript project that requires me to import a library, but I keep running into errors with npm every time I try to use it. Here is the error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Combining D3 and D3plus in an Angular web application: A complete guide

I'm currently integrating d3Plus sample code () into my angular-based webapp. This is the initial setup code: angular.module('UI', ['UI.controllers', 'UI.directives']); angular.module('d3Plus', ['d3' ...

What is the process for transferring an object to a different file?

Currently, I am working on a web application using Node.js. In my project, I have two main files. The first one is Server.js, where I handle server actions such as going online. The second file contains a large object filled with data. I successfully impo ...

What is the process for inserting a document into an array that is nested within another array?

My current dilemma revolves around a document (referred to as 'root') which contains an array of other documents ('stick'), each of which in turn contain another array of documents ('leaf'). Simply put: root{ stickChain[leaves ...

What is the best method for importing gltf files in three.js?

let manager = new THREE.LoadingManager(); const loader = new THREE.GLTFLoader(manager); // Function for setting up models with a position parameter // Load a glTF resource **line90** loader.load( // resource URL 'static/ElmTree.glt ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Problem with reordering rows in a PHP DataTable

While attempting to retrieve data from a database table and display it in a DataTable, I encountered the following error: DataTables warning: table id=example - Invalid JSON response. To learn more about this error, refer to http://datatables.net/tn/1 ...

Utilize dropdown1 to dynamically populate dropdown 2 in AngularJS

Here is the HTML code snippet I am currently working with: <select ng-controller="category" ng-model="selectedTestAccount" ng-options="c.category for c in categories track by c.categoryID" ></select> <select ng-controller="subcategory" ng ...

What is the best way to display changing session variables in PHP?

Purchase Page: This page allows customers to select business card orders in various foreign languages and customize their options. Whenever a user decides to add an extra card by clicking a button, javaScript dynamically includes new form fields. To ensur ...

Creating a dynamic video progress bar using three.js: A step-by-step guide

I'm struggling to create an interactive video progress bar using three.js and haven't been able to find any examples of it being done before. While I can successfully draw the progress of the video (using a plane with a canvas texture), I'm ...

It seems that the `to` required prop was missing in the `Link` component of React-Router

Currently, I am facing an issue while trying to integrate react-router. The error message I'm encountering is: Failed propType: Required prop to was not specified in Link. Check the render method of app. Unfortunately, I am unable to pinpoint ex ...

Adjust the width of the div by dragging one of its edges

My web application, which is built using Angular 2, features a two-panel layout. I am looking to implement the functionality to resize both panels by selecting either the right edge of the left panel or the left edge of the right panel. If you have any su ...