简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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