2017-06-03 58 views
1

我使用WebGL的Globe API及其旋轉動畫功能,但我希望用戶能夠通過雙擊地球來停止並重新啓動動畫。WebGL在當前位置重新開始動畫

目前我有一個運行的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); 
     } 


     }); 
    } 

而下面的代碼將停止並重新啓動雙擊動畫:雙

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; 
     } 
     } 
    }); 

停止和停止工作-Click。問題在於,當動畫停止時,時間仍然流逝,當動畫重新啓動時,地球的中心會立即轉移到它不會停止的位置。

如何確保在地球動畫重新啓動時,它會從當前中心而不是假想中心重新開始?

回答

0

因此,我終於通過簡單地創建一個名爲dontAllowTimeElapse的變量來解決這個問題,該變量初始設置爲false。當用戶停止動畫和重新啓動它,dontAllowTimeElapse被設置爲真:

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

      dontAllowTimeElapse = true; 
      performAnimation() 
      } 

在動畫代碼,如果dontAllowTimeElapse是真實的,所經過的時間被複位到0,這意味着從它是其中動畫重新啓動停止。一旦新的中心設置,時間流逝再次被允許:

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