You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Three JS如何为每个随机生成的对象设置X、Y轴随机旋转速度?

实现步骤

  1. 声明一个数组存储所有生成的球体实例,方便后续在动画帧中批量更新旋转状态
  2. 生成球体时为每个实例添加自定义的rotationSpeed属性,三个轴的速度直接用Three.js内置的THREE.MathUtils.randFloatSpread()方法生成,传入参数0.01即可得到取值范围在-0.005~0.005的随机值
  3. 在animate动画循环中遍历所有球体实例,按照各自的旋转速度更新旋转角度

修改后完整代码

// 新增:存储所有球体实例
const stars = [];

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);
  // 新增:为每个球体设置随机旋转速度,范围-0.005~0.005
  star.rotationSpeed = {
    x: THREE.MathUtils.randFloatSpread(0.01),
    y: THREE.MathUtils.randFloatSpread(0.01),
    z: THREE.MathUtils.randFloatSpread(0.01)
  };
  scene.add(star);
  // 新增:存入数组方便后续遍历更新
  stars.push(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;

    // 新增:批量更新所有球体的旋转状态
    stars.forEach(star => {
      star.rotation.x += star.rotationSpeed.x;
      star.rotation.y += star.rotationSpeed.y;
      star.rotation.z += star.rotationSpeed.z;
    });
  
    renderer.render(scene, camera);
  }
  
animate();

内容的提问来源于stack exchange,提问作者Cr3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:27:04