简体   繁体   中英

How do I randomize the length of vertices in three.js meshes?

I'm trying to randomize a mesh in three.js similar to this codepen I saw earlier today (the planets have kind of distorted/irregular edges). I tried reproducing this effect in a codepen I made (by blatantly copying a little code snippet from the codepen linked before) and changed the parameters to fit to mine (Look at line 56). As you can see the desired effect doesn't appear and breaks the code.

This is the part that won't work:

var noise = randomRange(1,5);
for(var i=0; i<Ico.vertices.length; i++){
      var v = Ico.vertices[i];
      v.x += -noise/2 + Math.random()*noise;
     v.y += -noise/2 + Math.random()*noise;
     v.z += -noise/2 + Math.random()*noise;
   };

Is there anything I didn't take into account here? Any help is greatly appreciated.

This is how you should approach your problem:

function randomRange(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

//Geometry

var geometry = new THREE.IcosahedronGeometry(25, 3);

var noise = randomRange(1,5);
for(var i=0; i<geometry.vertices.length; i++){
  var v = geometry.vertices[i];
  v.x += -noise/2 + Math.random()*noise;
  v.y += -noise/2 + Math.random()*noise;
  v.z += -noise/2 + Math.random()*noise;
};

//Meshes

var Ico = new THREE.Mesh(geometry, cyanMat);
Ico.rotation.z = 0.5;

Instead of

var Ico = new THREE.Mesh(
new THREE.IcosahedronGeometry(25,0), cyanMat);
Ico.rotation.z = 0.5;

put

function randomRange(min,max) {
    return Math.floor(Math.random()*(max-min+1)+min);
}

var icoGeom = new THREE.IcosahedronGeometry(25,1);
var noise = randomRange(5,10);
console.log(icoGeom);
icoGeom.vertices.forEach(function(vertex){
  console.log(vertex);
  vertex.x += Math.random()*noise - noise/2;
  vertex.y += Math.random()*noise - noise/2;
  vertex.z += Math.random()*noise - noise/2;
});

and yes, you forgot to copy/paste the randomRange() function.

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