45

I'm trying to change the color of a cube based on a variable. I created two cubes and I want to change their color depending on the distance between them.

The cubes are created like this:

geometry = new THREE.CubeGeometry( 50, 50, 50 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
cube = new THREE.Mesh( geometry, material );
scene.add( cube );

Now I tried something like this:

if(distance > 20)
{
cube.material.color = 0xffffff;
}

But it does not work. I looked in the examples but couldn't find anything appropriate.

WestLangley
  • 102,557
  • 10
  • 276
  • 276
user1952715
  • 451
  • 1
  • 4
  • 3

4 Answers4

84

You are not specifying the color value correctly.

cube.material.color.setHex( 0xffffff );
WestLangley
  • 102,557
  • 10
  • 276
  • 276
  • 2
    You can also use the base-10 integer equivalent as the parameter for setHex, as the two equate in JS. – andrewb May 12 '16 at 00:47
16
cube.material.color 

will give you the THREE.Color object:

Color

which has a bunch of methods you can use to set the color.

xxx
  • 1,153
  • 1
  • 11
  • 23
k26dr
  • 1,229
  • 18
  • 15
9

My suggestion is attach a function to your object and then you can change the color of object during runtime easily.
Based on your code

geometry = new THREE.CubeGeometry( 50, 50, 50 );
material = new THREE.MeshBasicMaterial( { color: 0xff0000, wireframe: true } );
cube = new THREE.Mesh( geometry, material );

//here is the funcion defined and attached to the  object
cube.setColor = function(color){
     cube.material.color.set(color);
}


cube.setColor(0xFFFFFF)  //change color using hex value or
cube.setColor("blue")    //set material color by using color name

scene.add( cube );
Harun ERGUL
  • 5,770
  • 5
  • 53
  • 62
0

In the material part you can provide a hexadecimal color value Like this meshMaterial = new THREE.MeshBasicMaterial({color:0xfffff}) In the following code hexadecimal value (0xffffff) is of colour white

It's Joker
  • 65
  • 10