2013-01-06 64 views
15

我试图根据变量更改立方体的颜色。我创建了两个立方体,我想根据它们之间的距离来改变它们的颜色。在three.js中更改立方体的颜色

立方体创建这样的:

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

现在,我想是这样的:

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

但它不工作。我看了一些例子,但找不到合适的东西。

回答

50

您没有正确指定颜色值。

cube.material.color.setHex(0xffffff); 
+1

您还可以使用基10的整数相当于为setHex参数
,因为这两个等同的JS。 – andrewb

6
cube.material.color 

会给你THREE.Color对象:

http://threejs.org/docs/#Reference/Math/Color

其中有一堆你可以用它来设置颜色的方法。

+2

在链接死亡的情况下,需要在答案中使用实际方法。 – andrewb

+0

链接死了,正确的答案是color.set(),'cube.material.color.set(color)' –

1

我的建议是给你的对象附加一个函数,然后你可以很容易地在运行时改变对象的颜色。基于您的代码

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 = new THREE.Color(color); 
} 


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

scene.add(cube); 
+1

不要实例化一个新的'Color'。使用'cube.material.color.set(color)'。 – WestLangley