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

React Three.js渲染问题:计算得到的半径为NaN

解决Three.js中THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN报错

问题原因

报错的核心是你创建的Float32Array长度不是3的整数倍。每个星星顶点需要x、y、z三个坐标值,当数组长度无法被3整除时,最后一组顶点会缺失1-2个坐标分量,导致Three.js计算包围球时出现NaN值。你当前用的5000作为数组长度,5000 % 3 = 2,恰好剩余两个无效的空值。

解决方案

将Float32Array的长度设置为3的整数倍,确保每个顶点都拥有完整的x、y、z坐标。可以直接指定3的倍数作为数组长度,或者通过「点数×3」的方式计算:

修改后的Stars组件代码

import * as random from "maath/random/dist/maath-random.esm";
...
const Stars = (props) => {

  const ref = useRef();
  // 1666个星星,每个占3个数组元素,总长度4998(3的倍数)
  const [sphere] = useState(() =>
    random.inSphere(new Float32Array(1666 * 3), { radius: 1.2 })
  );

  useFrame((state, delta) => {
    ref.current.rotation.x -= delta / 10;
    ref.current.rotation.y -= delta / 15;
  });

  return (
    <group rotation={[0, 0, Math.PI / 4]}>
      <Points ref={ref} positions={sphere} stride={3} frustumCulled {...props}>
        <PointMaterial
          transparent
          color="#f272c8"
          size={0.002}
          sizeAttenuation={true}
          depthWrite={false}
        />
      </Points>
    </group>
  );
};

额外验证(可选)

如果担心生成的数组中仍存在NaN,可以在生成后添加校验:

const sphereArray = random.inSphere(new Float32Array(1666 * 3), { radius: 1.2 });
// 检查是否有NaN值
const hasNaN = Array.from(sphereArray).some(val => isNaN(val));
if (hasNaN) console.warn("数组中存在NaN值");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:53:00