在three.js中更改立方体的颜色。

46
我试图根据一个变量来改变一个立方体的颜色。我创建了两个立方体,我想根据它们之间的距离来改变它们的颜色。
这些立方体是这样创建的:
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;
}

但是它不起作用。我在例子中找了找,但没有找到合适的东西。
4个回答

85

您没有正确指定颜色值。

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

2
你也可以使用十进制整数等价物作为 setHex 的参数,因为在 JS 中两者是相等的。 - andrewb

17
cube.material.color 

会给你一个THREE.Color对象:

Color

它有许多方法可用于设置颜色。


2
如果链接失效,需要在答案中包含实际的方法。 - andrewb
链接失效,正确答案是color.set(),'cube.material.color.set(color)'。 - Ian Wise

10

我的建议是将一个函数附加到你的对象上,这样你就可以在运行时轻松地改变对象的颜色。
基于你的代码

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 );

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

0
在材料部分,您可以提供十六进制颜色值 像这样 meshMaterial = new THREE.MeshBasicMaterial({color:0xfffff}) 在下面的代码中,十六进制值(0xffffff)是白色的颜色

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接