我如何重写代码来为我的球体分配一个随机的颜色?


function randomColor(){
var randomcolor = new Color().setRGB(Math.random(), Math.random(), Math.random());
return{ randomcolor }
};
randomColor();
var geometrySphere = new SphereGeometry(10, 15);
var materialSphere = new MeshStandardMaterial({
color: randomColor,
flatShading: true,
wireframe: true,
});
var meshSphere = new Mesh(geometrySphere, materialSphere);
scene.add(meshSphere);

如果我control .log color函数,它会给我一个颜色,但它不会把它分配给立方体。

您使用函数本身作为颜色的值,您应该使用返回值,并且Math.random()返回0到1之间的数字,因此颜色将始终为黑色。

下面的代码应该有帮助:

function randomColor(){
var randomcolor = new Color().setRGB(Math.random() * 255, Math.random() * 255, Math.random() * 255);
return{ randomcolor }
};
var color = randomColor();
var geometrySphere = new SphereGeometry(10, 15);
var materialSphere = new MeshStandardMaterial({
color: color,
flatShading: true,
wireframe: true,
});
var meshSphere = new Mesh(geometrySphere, materialSphere);
scene.add(meshSphere);

最新更新