Manipulating the material of a single mesh in Three.js causes a ripple effect, impacting all materials within

I am encountering an issue with selecting a random mesh in my THREE JS scene from an array. When I try to select and modify the properties of what seems to be an individual Mesh within the scene, it affects all meshes, even though there are no merged polygons in this example. Any thoughts on what could be causing this problem with selecting a random mesh?

var buildingObjs = [];

for ( var i = 0; i < 20; i ++ ) {
                var geometry = new THREE.BoxGeometry( 1, 1, 1 );
                geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.5, 0 ) );

                var building = new THREE.Mesh( geometry, material );
                var geo = new THREE.EdgesGeometry( building.geometry ); // or WireframeGeometry
                var mat = new THREE.LineBasicMaterial( { color: 0xcfcfcf } );
                var wireframe = new THREE.LineSegments( geo, mat );
                building.add( wireframe );

                var value = 1 - Math.random() * Math.random();
                var color = new THREE.Color().setRGB( value + Math.random() * 0.1, value, value + Math.random() * 0.1 );

                var top = color.clone().multiply( light );
                var bottom = color.clone().multiply( shadow );

                building.position.x = Math.floor( Math.random() * 200 - 100 ) * 10;
                building.position.z = Math.floor( Math.random() * 200 - 100 ) * 10;
                building.rotation.y = Math.random();
                building.scale.x = building.scale.z = Math.random() * Math.random() * Math.random() * Math.random() * 50 + 10;
                building.scale.y = ( Math.random() * Math.random() * Math.random() * building.scale.x ) * 8 + 8;

                buildingObjs.push(building);
                scene.add(building);
                
            }

function randomBuildingSelector()
        {
              
            var randomBuilding = buildingObjs[Math.floor(Math.random()*buildingObjs.length)];
            return randomBuilding;
        }

        function startAniLabels() {
            var selectedMesh = undefined;
            var tt = setInterval(function(){ 
                selectedMesh = randomBuildingSelector();
                console.log(selectedMesh);
                selectedMesh.material.color.setHex( 0x333333 );
             }, 5000);

            
        }

A code snippet in the fiddle below:

https://jsfiddle.net/60j5z9w3/

All buildings change color, but only one should change.

Answer №1

The issue arises from your usage of the material variable. By utilizing a single material for all buildings, any color changes will affect every building. Here's a simplified version of your code snippet to illustrate this point:

// Create 1 material
var material = new THREE.MeshPhongMaterial();

for (var i = 0; i < 2000; i++) {
    var geometry = new THREE.BoxGeometry( 1, 1, 1 );
    // Apply the same material to 2000 meshes
    var building = new THREE.Mesh( geometry, material );
}

// Modifying the color of the sole material also alters the color of all meshes
buildingObjs[500].material.color.setHex( 0x333333 );

If you intend to customize each mesh separately, you must generate a new material for each one.

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

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

React Foundation accordion not functioning properly

Utilizing Foundation accordion within my React component has presented a challenge. The code functions properly when rendering static HTML, but when attempting to render it dynamically through a loop, the accordions lose their clickability. React code fo ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

The error message SCRIPT1003 is indicating that a colon was expected

There are many questions with this title, but I have a unique one for you. An error message "SCRIPT1003: Expected ':' (1,78)" pops up when I launch my website. I am using webpack and typescript in my project. Below is my tsconfig: { "co ...

Utilize try-catch or async-await within useEffect when testing with Jest

I am currently setting up my initial unit tests using JEST. I've installed Jest Fetch Mock but unfortunately, I keep encountering an error stating "The promise rejected with reason FetchError". After doing some research, it seems like I may need to i ...

Omit a certain td element from the querySelectorAll results

Greetings! I am currently working with an HTML table and I need to figure out how to exclude a specific td element from it, but I'm not sure how to go about it. Here's the HTML code: <table id="datatable-responsive" c ...

Executing javascript function on hyperlink click

When using Response.Write to print a hyperlink like "Update", I am in need of a JavaScript function that will be triggered when the hyperlink is clicked. Can someone offer a solution for this issue? ...

What are the security benefits of using Res.cookie compared to document.cookie?

When it comes to setting cookies to save data of signed in members, I faced a dilemma between two options. On one hand, there's res.cookie which utilizes the Express framework to set/read cookies on the server-side. On the other hand, there's d ...

Is there a way to include text in a video similar to the style used by PayPal?

PayPal uses the tagline "You Make it, We'll Pay It" displayed on top of a video with a subtle play button located in the corner. By clicking this play button, the video initiates playback and smoothly transitions from a dark overlay to the video itsel ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

Adding Tooltips to Your Bootstrap 5 Floating Labels Form: A Step-by-Step Guide

Can you include tooltips or popovers in Bootstrap 5 floating labels text? I've set up a form with floating form fields and I'd like to provide instructions for certain fields using tooltips or popovers. I can make it work with the standard form ...

Asynchronous waterfall call in Node.js to call the method before

Is it possible to invoke a previous method within async.waterfall from a subsequent method? async.waterfall([ function (callback) { }, function (reservationStatus, callback) { }, function (reservationStatusList, f ...

Issue: "fourSquareService.retrieveLocations does not exist as a function"

Struggling with AngularJs - How to Utilize Factory Alongside Form Input in URL for Data Fetching? This is my first time asking a question here. I've been diving into Angular and wanted to organize my services by separating them into different files. ...

node.js issue with chalk package

**When I want to use the chalk package in node.js, I encounter the following issue:** index.js const chalk = require('chalk'); console.log(chalk.bgRed.inverse("hello world")); console.log(chalk.blue.inverse('Hello') + &ap ...

Exploring the power of AngularJS with JavaScript and utilizing the $scope

After spending the entire day trying to solve this issue, it seems like I might be missing something simple. Here's the problem at hand: I have a well-structured Nodejs/AngularJS application that utilizes Jade for templating. The server performs certa ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Comparing the distinction between assigning values to res and res.locals in a Node.js application using Express

Greetings! I am inquiring about the utilization of res (Express response object) and res.locals in Express. During my exploration of nodejs, I came across a code snippet that consists of a middleware (messages.js), a server (app.js), and a template (messa ...

Retrieve the initial class of an element using either jQuery or JavaScript

I need help with a jQuery function that is not working properly. I have 3 anchors with corresponding divs, and when I click on one of the anchors, I want to display the contents of the corresponding div. The anchors are as follows: <a class="home share ...

Ways to update a component's state by clicking a button located on a different component

Seeking help with changing a parent state value when clicking a button. Although there are numerous similar queries out there, I'm really struggling to grasp the concept. I've attempted lifting the state up but haven't quite nailed it yet. ...