A
A
Andrey Shuvalov2017-01-23 16:23:09
JavaScript
Andrey Shuvalov, 2017-01-23 16:23:09

How to play and stop animation of individual three.js objects?

I recently started to study three.js, downloaded an example from off site , tried to make an animation stop if the object is "assembled" and play the animation when the button is clicked.

function animate() {
      if (anim){
      id = requestAnimationFrame( animate );
      render();
      stats.update();
        if (uniforms.amplitude.value <= 0.0005) {
          anim = false;
        }
      }
    }
    function render() {
      timer += 0.001;
      uniforms.amplitude.value = 1.0 + Math.sin( timer* 50);
      controls.update();
      renderer.render( scene, camera );
    }
    document.getElementById("but").addEventListener("click", function(){
      anim = true;
      animate();
    });

If you completely stop the entire animation, then everything is fine, but you cannot, for example, rotate the camera around the object.
I tried to change the animation function, but in this case, after each click on the button, the animation "accelerates", and "fps" in the upper left corner is written not 60, as usual, but 200, 300, 600+, etc.
function animate() {
      id = requestAnimationFrame( animate );
      if (anim){
        timer += 0.001;
        uniforms.amplitude.value = 1.0 + Math.sin( timer* 50);
        controls.update();
        renderer.render( scene, camera );
        if (uniforms.amplitude.value <= 0.0005) {
          anim = false;
        }
      } else { 
        render(); 
      }
      stats.update();
    }
    function render() {
      controls.update();
      renderer.render( scene, camera );
    }

Tell me what is the problem with this acceleration of animation, or how can animations of individual objects be played differently.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Shuvalov, 2017-01-25
@Odenzzz

In general, I managed to fix this by stopping the animation before each re-call of it

function animate() {
          if (anim) {
            cancelAnimationFrame(id)
            id = requestAnimationFrame( animate );
            explode();
          } else {
            cancelAnimationFrame(id)
            id = requestAnimationFrame( animate );
            render(); 
          }
      stats.update();
    }

I don’t know how correct or optimal it is, but at least it works as it should.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question