试图在for循环的每次迭代中强制渲染三个.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 );
}
}
}

但它也不起作用。显然,我在导致Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17requestAnimationFrame的两个调用之间也存在冲突

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

您的最后一个函数即将实现。在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的速度运行。

最新更新