Search code examples
javascriptthree.jstween.js

How to change material color for only one object in THREE.js


I'm editing a program wrote in Three.js and Tween.js. I try to find the solution here and on the web, without results. I have a lot of object (cones) create by THREE.Mesh and there is a little script that every 5 second select one of these and change, for few time, its dimension. I would like change also the color, but i have some problems. If i try to change the color, this change for every object, but i want that change only for the object selected by the script.

this is the code 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;
});

This is the function that change the dimension of 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


Solution

  • You are making clones of one cone. During cloning meshes share link to one material. If you need to change colors of shapes separately then you need to clone a material for each object also. It think that should be enough:

    var m = baseMesh.clone();
    m.material = baseMesh.material.clone();