Search code examples
javascriptjqueryanimationwebgl-globe

WebGL Earth restart animation at current location


I'm using WebGL's Globe API and its rotating animation capability, but I want the user to be able to stop and restart the animation by double-clicking on the globe.

Currently I have the following animation code that runs onload:

function performAnimation() {
      requestAnimationFrame(function animate(now) {
        if (animated) {
          var c = earth.getPosition();
          var elapsed = before? now - before: 0;
          before = now;
          earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
          requestAnimationFrame(animate);
        }


      });
    }

And the following code stops and restarts the animation on double-click:

performAnimation()
    var animated = true;
    var touchtime = 0;

    $('#globe').on('click', function() {
      if(touchtime == 0) {
        touchtime = new Date().getTime();
      } else {
        if(((new Date().getTime()) - touchtime) < 200) {
          if (animated) {
            animated = false;
          } else {
            animated = true;
            performAnimation()
          }
          console.log(animated);
          //alert(animated);

          touchtime = 0;
        } else {
          touchtime = 0;
        }
      } 
    });

The stop and stop works on double-click. The problem is that when the animation is stopped, the time still elapses, and when the animation is restarted the globe's center is immediately shifted to the position it would have been in had it not stopped.

How can I ensure that when the globe animation restarts, it restarts from its current center and not the hypothetical center?


Solution

  • So I've finally solved this issue by simply creating a variable called dontAllowTimeElapse that is initially set to false. When the user stops the animation and restarts it, dontAllowTimeElapse is set to true:

             if (animated) {
                animated = false;
              } else {
                animated = true;
    
                dontAllowTimeElapse = true;
                performAnimation()
              }
    

    In the animation code, if dontAllowTimeElapse is true, the time elapsed is reset to 0, which means the animation restarts from where it was stopped. Once the new center is set, time elapse is allowed again:

             if (dontAllowTimeElapse) {
                elapsed = 0;
              }
              before = now;
              earth.setCenter([c[0], c[1] + 0.1*(elapsed/30)]);
              dontAllowTimeElapse = false;
              requestAnimationFrame(animate);