简体   繁体   English

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

[英]How do I rewrite the code to assign a random color to my sphere?

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

If I controll.log the color function it gives me a color, but it does not assign it to the cube.如果我 controll.log 颜色 function 它会给我一种颜色,但不会将其分配给立方体。

You are using the function itself as value for color, you should use the return value, and Math.random() returns a number between 0 and 1 so the color is going to be always black.您正在使用 function 本身作为颜色值,您应该使用返回值,并且Math.random()返回一个介于 0 和 1 之间的数字,因此颜色将始终为黑色。

The code below should help:下面的代码应该有所帮助:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM