Modifying the color of an individual object in THREE.js: Step-by-step guide

I am currently working on editing a program that uses Three.js and Tween.js. Despite my efforts to find a solution both here and online, I have not been successful. The program involves creating multiple objects (cones) using THREE.Mesh, with a script that selects one of these objects every 5 seconds and temporarily changes its dimensions. However, I am facing difficulties when trying to change the color of the selected object only, as the color change affects all objects instead.

Below is the code snippet used to create the objects:

VIS.createCityMarkers = function( cities ){

  var material = new THREE.MeshPhongMaterial({
      color: 0xffdb85,
      specular: 0xff6c00,
      shininess: 3,
      shading: THREE.FlatShading
 });

var baseMesh = new THREE.Mesh( new THREE.CylinderGeometry( 0.2, 0.0, 0.4, 32, 1 ), material );
baseMesh.geometry.applyMatrix( new THREE.Matrix4().makeRotationX( -Math.PI * 0.5 ) );

var cityLookup = {};

  var group = new THREE.Group();
  _.each( cities, function( cc, name ){
  var g = new THREE.Group();
  var m = baseMesh.clone();
  g.add( m );
  var p = Coordinates.latLongToVector3( cc.lat, cc.long + 90, 10.8 );   
  g.position.copy( p );
  g.lookAt( group.position );
  m.name = name;
  group.add( g );
  cityLookup[ name ] = m;
});

Here is the function responsible for changing the dimension of the selected object (m):

function highlightCityMesh(m){

  var s = {
    scale: 1.0,
    up: 0.0,
    color: 0xffdb85
  };
  new TWEEN.Tween( s )
  .to({
    scale: 3.0,
    up: 2.0,
    color: 0xc00000
  }, 2000 )
  .easing( TWEEN.Easing.Elastic.Out )
  .onUpdate( function(){
    m.scale.set( s.scale, s.scale, s.scale );
    m.position.z = -s.up;
    m.material.color.setHex(s.color);
  })
  .start();

  m.update = function(){
    this.rotation.z = Date.now() * 0.001;
  };
}

Thank you

Answer №1

When creating duplicates of a cone, keep in mind that the meshes will be sharing a reference to the same material. If you want to independently change the colors of each shape, you will need to create duplicate materials for each object. The following code snippet should help you achieve this:

var newClone = originalMesh.clone();
newClone.material = originalMesh.material.clone();

Answer №2

In the scenario where you have multiple children with the same material color and want to change the material color of only one specific mesh, the following code demonstrates how to achieve this:

var clonedMaterial = selectedMesh.material.clone()
clonedMaterial.emissive.r = 0.92; // or clonedMaterial.color
clonedMaterial.emissive.g = 0.92;
clonedMaterial.emissive.b = 1;
selectedMesh.material = clonedMaterial;

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 are the steps to incorporate a MenuItem within a div container instead of being a direct child of the Select component in Material-UI?

Embarking on my MUI journey, I am exploring how to utilize Select and MenuItem in tandem to create a checked dropdown functionality with the help of this reference link. My goal is to structure a header, body div for MenuItems, and a footer inside the sele ...

Getting the href values of dynamically changing links with Selenium in Python: A step-by-step guide

Is there a way to extract all hrefs(links) located in anchor tags using JavaScript code with Selenium Python, especially when these links are dynamically updated? The tag I am trying to click on is as follows: enter image description here I have managed t ...

Creating a Custom Form Control in Angular 2 and Implementing Disable Feature

I have developed a unique custom control using ControlValueAccessor that combines an input[type=text] with a datepicker. While the template-driven forms accept it without any issues, the situation changes when implementing the model-driven approach (react ...

How to capture a change event in a dynamically loaded element using JQuery

I am facing an issue with dynamically added rows in my table. Each row contains a select option, and I need to trigger an action when the select is changed. However, since the rows are loaded after the page load, my function does not work as expected. < ...

Vue.js Google Places Autocomplete Plugin

I'm currently working on integrating Google Places Autocomplete with Vue.js. According to the API documentation, the Autocomplete class requires an inputField:HTMLInputElement as its first parameter, like shown in their example: autocomplete = new g ...

Obtaining JSON data from a PHP script using AngularJS

I've been exploring an AngularJS tutorial on a popular website called w3schools. Check out the tutorial on w3schools After following the tutorial, I modified the script to work with one of my PHP scripts: <!DOCTYPE html> <html > <sty ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

Utilizing JavaScript within my WordPress site

I'm experiencing some issues with my JavaScript code in WordPress. I have been trying to use the following code on my page, but it doesn't seem to work properly. Can someone please guide me on how to integrate this code within my WordPress page? ...

Blip Scripts: Converting JSON to JavaScript - Dealing with Undefined Arrays

I am currently working on a project to develop a bot on Blip. There are certain parts where I need to send a request to an API and then use a JavaScript script to extract elements from the JSON response. The JSON response I received from the API is stored ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Exclude previous dates from the front end of ACF date picker

I am using Advanced Custom Fields to post job ads, and I have incorporated a date picker field for the end date of each job ad. <?php if (have_rows('jobs', 'option')): ?> <?php $now = time(); ?> <div i ...

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Crop box overlaying video background

Utilizing jCrop to establish a crop region for a video element. My goal is to make the video section within the crop area fill a container with identical proportions, but I'm encountering challenges with the mathematical calculations. The sizes of th ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Simultaneous asynchronous access to a single object

I have been working with JS/TS for quite some time now, but the concept of race conditions still perplexes me. I am currently attempting to execute the following logic: class Deployer { protected txDataList: Array<TXData>; constructor() { this ...

Nextjs style import function properly on the development server, but faces issues when deployed to production environments

import "../styles.css"; import styles from "react-responsive-carousel/lib/styles/carousel.min.css"; import "react-owl-carousel2/lib/styles.css"; import { Provider } from "react-redux"; import store from "../store/store" function App({ Component, pageProps ...

Attempting to incorporate icons into a Material UI table design

Hello, I've incorporated a Material UI table into one of my projects with a design concept similar to this - https://i.stack.imgur.com/i6Fsj.png I'm aiming to include icons within the tables. Here's the code I've worked on so far - ...

In search of a tool that enables horizontal scrolling of content

I am on the lookout for a piece of Javascript code that can be integrated into my website to enable me to horizontally scroll content either from left to right or right to left. Although I found this script here: It offers the fundamental functionality th ...

What is the best method for retaining the complete YQL outcome within a JavaScript object?

I am trying to store the output of my YQL Query in a JavaScript object Here is my query: SELECT * FROM html WHERE url="http://myurl.com" and xpath="/html/body/center/table[1]/tr" Can someone guide me on how to proceed? I have gone through the YQL docu ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...