0

我刚开始使用three.js。我使用在three.js 主网站上找到的代码片段组装了一个测试。

根据我制作的方程式,我有一堆几何图形(球体)代表在循环内改变位置的粒子。我试图通过这种代码渲染每次迭代:

function simulate() {
    for (var j = 0 ; j < Nb ; j++ ) {           
        // update the geometries positions
        ...
        render();
    }
}

但渲染没有完成,而是在经过所有迭代后执行,当进入animate函数时,调用后simulate

function animate() {
    render();
    requestAnimationFrame( animate );
}

实际上,如果我在我的 chrome 浏览器的 javascript 控制台中一步一步地进行渲染,就会发生这种情况。

所以我试图改变我的代码,这样我就可以requestAnimationFrame在我的循环中使用,这样:

function simulate() {
    for (var j = 0 ; j < Nb ; j++ ) {           
        this.internalRenderingLoop = function() {
            // update the objects shapes and locations
            ...
            render();
            requestAnimationFrame( this.internalRenderingLoop );
        }
    }
}

但它也没有工作。我显然也有两个电话之间的冲突requestAnimationFrame导致Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17

所以问题是:有没有办法在我的simulate函数的每次迭代中强制渲染,或者我是否需要重构我的代码,以便每次更新几何位置的调用都在animateorrender函数中进行?

4

1 回答 1

2

您的最后一个功能即将完成。在您的 for 循环中,您只是覆盖了 internalrendering 循环函数,而没有执行更改。此外,如果您在形状更新代码中使用 j 变量,则需要稍微增加它。像这样的东西怎么样(未经测试,但你明白了):

var j = 0; // need to be outside function to have proper scope
function simulate() {
  j++;
  if (j == Nb) { return; } // stop

  // update the objects shapes and locations

  render();
  requestAnimationFrame(simulate);      
}

您根本不需要 animate() 函数,因为您已经在模拟 () 中进行动画处理。

您的模拟速度也将取决于帧速率,因此为了更好地控制模拟速度,您可以将最后一行函数替换为:

window.setTimeout( function() { requestAnimationFrame(simulate); }, 1000 / 25);

这应该以大约 25 FPS 的速度运行。

于 2012-12-11T07:53:43.880 回答