我刚开始使用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
函数的每次迭代中强制渲染,或者我是否需要重构我的代码,以便每次调用更新几何位置都在{{ 1}}或animate
功能?
答案 0 :(得分:2)
你的最后一个功能就在那里。在你的for循环中,你只是覆盖了内部渲染循环函数而没有得到执行的更改。此外,如果您在形状更新代码中使用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()函数,因为你已经在simulate()中进行了动画制作。
您的模拟速度也取决于帧速率,因此为了更好地控制模拟速度,您可以用以下内容替换最后一行功能:
window.setTimeout( function() { requestAnimationFrame(simulate); }, 1000 / 25);
这应该大约以25 FPS运行。