如何在three.js中优化多个sphereGeometry的渲染?

时间:2014-02-25 23:13:30

标签: javascript optimization three.js webgl

我想在three.js中优化sphereGeometry的渲染,因为它在我的程序中成为瓶颈。 javascript程序如下所示:

var sphereThree = [];
for(var idSphere = 0; idSphere < numSphere; idSphere++){
    var sphereGeometry = new THREE.SphereGeometry(1.0);
    var sphereMaterial = new THREE.MeshLambertMaterial({color: 'rgb(255, 0, 0)'});

    sphereThree[idSphere] = new THREE.Mesh(sphereGeometry, sphereMaterial);

    sphereThree[idSphere].position.x = x[idSphere];
    sphereThree[idSphere].position.y = y[idSphere];
    sphereThree[idSphere].position.z = z[idSphere];

    scene.add(sphereThree[idSphere]);
}

如下列链接所述:
- Animateing a Million Letters Using Three.js
- Optimizing Three.js Performance: Simulating Tens of Thousands of Independent Moving Objects
他们指出,我们不应该单独添加对象,并且最好同时添加相同类型的对象,以进行优化。但是,由于我是这个领域的新手,因此在使用SphereGeometry时我不知道如何对此优化进行编码。

如果有人知道如何使用SphereGeometry编写这些代码,或者知道一种有效方法来渲染许多(10,000或更多)球体的人,你会教我们吗?

谢谢!

2 个答案:

答案 0 :(得分:16)

您可以像这样重复使用几何体和材质:

var sphereGeometry = new THREE.SphereGeometry(1.0);
var sphereMaterial = new THREE.MeshLambertMaterial({color: 'rgb(255, 0, 0)'});

var sphereThree = [];
for(var idSphere = 0; idSphere < numSphere; idSphere++){
    sphereThree[idSphere] = new THREE.Mesh(sphereGeometry, sphereMaterial);

    sphereThree[idSphere].position.x = x[idSphere];
    sphereThree[idSphere].position.y = y[idSphere];
    sphereThree[idSphere].position.z = z[idSphere];

    scene.add(sphereThree[idSphere]);
}

答案 1 :(得分:0)

如果球体的外观无关紧要,您还可以将widthSegments和heightSegments参数设置为低于默认值的值。 请参阅文档here

基本上做类似的事情:

var sphereGeometry = new THREE.SphereGeometry(1.0, 5, 4);

<强>更新 我忘了提一下,一旦你尝试了mrdoob的建议并且你想进一步优化就应该这样做。加速并不重要。