首页 > 解决方案 > 如何为创建的每个随机生成的对象创建随机 X 和 Y 旋转(三个 JS)

问题描述

我一直在使用三个 JS 作为我的主要 3d 对象渲染器进行我的个人项目,我想随机生成具有指定范围的随机 x、y 和 z 坐标的球体,我能够这样做,但现在我需要这些随机生成的对象中的每一个沿其 xy 和 z 具有从 0.005 到 -0.005 范围内的随机放置的旋转速度。但不知道如何解决这个问题,任何帮助将不胜感激,他是我的随机生成代码,也是我已经处理过的动画 3d 对象的代码:

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

标签: javascriptanimationthree.js

解决方案


您可以在创建时存储旋转的随机值并在每次渲染时对其进行动画处理。

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

在这里做了一个codepen:
https ://codepen.io/cdeep/pen/OJjVXqW


推荐阅读