Cr3
Cr3

Reputation: 159

How to create a random X and Y rotation for each randomly generated object that is created (Three JS)

I have been working on a personal project of mine using Three JS as my main 3d object renderer and I wanted to randomly generate spheres at random x, y, and z coordinates with a specified range, I was able to do so, but now I need each of these randomly generated objects to have a randomly placed rotation speed along its x y and z from a range of 0.005 to -0.005. But no clue how to approach this and any help would be greatly appreciated, he is my random generation code, and also the code to animate 3d objects I have already dealt with:

function randomStar(){
  const geometry = new THREE.SphereGeometry(0.25, 24, 24);
  const starMaterial = new THREE.MeshBasicMaterial({color: 0xffffff, wireframe: false});
  const star = new THREE.Mesh(geometry, starMaterial);

  const [x,y,z] = Array(3).fill().map(() => THREE.MathUtils.randFloatSpread(150));
  star.position.set(x,y,z);
  star.rotation.x += 0.01;
  star.rotation.y += 0.01;
  scene.add(star);
}
Array(350).fill().forEach(randomStar);

function animate() {
    requestAnimationFrame( animate );
  
    torus.rotation.y += 0.005;
    torus.rotation.x += 0.005

    torusOne.rotation.x += 0.002
    torusOne.rotation.y += 0.005;
    torusTwo.rotation.y+= 0.005;
    torusTwo.rotation.x += 0.002


    globe.rotation.y += 0.001
    // controls.update();
  
    renderer.render(scene, camera);
  }
  
   animate();

Upvotes: 2

Views: 557

Answers (1)

Deep
Deep

Reputation: 549

You could store the random value of rotation on creation and animate it on each render.

star.userData.rx = Math.random() * 0.01 - 0.005;
star.userData.ry = Math.random() * 0.01 - 0.005;
star.userData.rz = Math.random() * 0.01 - 0.005;

...

animate() {
  star.rotation.x += star.userData.rx;
  star.rotation.y += star.userData.ry;
  star.rotation.z += star.userData.rz;
}

Made a codepen here:
https://codepen.io/cdeep/pen/OJjVXqW

Upvotes: 2

Related Questions