I am just starting using three.js. I have assembled a test using pieces of code I’ve found on three.js main website.
I have a bunch of geometries (spheres) representing particles which positions are changed inside a loop, according to an equation I made.
I tried to render each iteration through this kind of code:
function simulate() {
for (var j = 0 ; j < Nb ; j++ ) {
// update the geometries positions
...
render();
}
}
but the rendering was not done, instead it was performed after going through all the iterations, when entering the animate function, called after simulate
function animate() {
render();
requestAnimationFrame( animate );
}
Actually the rendering would happen if I was going step by step in the javascript console of my chrome browser.
So I tried to change my code so that I could use requestAnimationFrame inside my loop, that way:
function simulate() {
for (var j = 0 ; j < Nb ; j++ ) {
this.internalRenderingLoop = function() {
// update the objects shapes and locations
...
render();
requestAnimationFrame( this.internalRenderingLoop );
}
}
}
but it did not work either. I also apparently have a conflict between both calls of requestAnimationFrame leading to Uncaught Error: TYPE_MISMATCH_ERR: DOM Exception 17
So the question is: is there a way to force the rendering at each iteration in my simulate function or do I need to refactor my code so that each call to update the geometries positions is made in the animate or render function?
Your last function is nearly there. In your for loop, you are just overwriting the internalrendering loop function without it getting a change to execute. Also if you are using the j variable in your shape update code, you need to increment it a bit differently. How about something like this (untested, but you get the idea):
You won’t need animate() function at all because you are already doing the animating in simulate().
Your simulation speed will also depend on framerate, so to have more control on simulation speed you can replace the last line of function with something like:
This should run it approximately at 25 FPS.