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

Three.js中THREE.Geometry转BufferGeometry遇NaN问题求助

将THREE.Geometry替换为THREE.BufferGeometry生成随机点的正确方法

你出错的核心问题是:Float32BufferAttribute接收的不是Vector3对象数组,而是扁平的一维数值数组——每个点的x、y、z坐标需要依次存入一个连续的数组中,不能直接存放Vector3对象。另外要注意,BufferGeometry中没有vertices属性,对应的标准属性名是position。

正确实现步骤

  1. 创建长度为 点数×3 的Float32Array(每个点需要x、y、z三个数值)
  2. 循环生成随机Vector3,将其坐标值依次写入数组的对应位置
  3. 用该数组创建Float32BufferAttribute,并指定每个顶点的分量数为3
  4. 为BufferGeometry设置position属性

完整代码示例

const pointsGeometry = new THREE.BufferGeometry();
// 1000个点,每个点3个坐标,总长度3000
const positions = new Float32Array(1000 * 3);

for (let i = 0; i < 1000; i++) {
    const vector = new THREE.Vector3();
    // 替换为你的随机坐标生成逻辑
    vector.x = Math.random() * 200 - 100;
    vector.y = Math.random() * 200 - 100;
    vector.z = Math.random() * 200 - 100;

    // 计算当前点在数组中的起始索引
    const startIndex = i * 3;
    // 将坐标写入数组,也可以用vector.toArray(positions, startIndex)简化
    positions[startIndex] = vector.x;
    positions[startIndex + 1] = vector.y;
    positions[startIndex + 2] = vector.z;
}

// 设置position属性,第二个参数3表示每个顶点由3个数值组成
pointsGeometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));

关键细节说明

  • BufferGeometry使用position属性替代旧Geometry的vertices,这是WebGL的标准顶点属性名称,Three.js会自动识别并用于渲染
  • Float32BufferAttribute要求输入的是连续的数值类型数组(如Float32Array),不能直接传入Vector3对象数组,这也是你之前得到NaN的原因
  • 可以用Vector3.toArray()方法快速将坐标写入数组,效果和手动赋值完全一致,代码更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:51:31