2017-09-02 41 views
0

我模擬jQuery的保齡球遊戲。所以,我扔球(通過動畫功能),當它擊中一個引腳時,我模擬它跳過(也通過動畫功能)。但我只能讓它旋轉。我希望它落在原地,向左或向右。像this一樣。這是針動畫jQuery代碼:模擬對象翻倒使用jQuery

this.animation = function (pinID) { 
    var rdm = ((Math.random()*10)+1); 
    var degree; 
    if (rdm <= 5) 
     degree = -90; 
    else 
     degree = 90; 
    $(pinID).animate({ deg: degree }, 
    { 
     duration: 1000, 
     step: function (now) { 
      // In the step-callback (that is fired each step of the animation), 
      // the pin will rotate to the current degree of the animation 
      $(pinID).css({ 
       transform: 'rotate(' + now + 'deg)' 
      }); 
     }, 
     complete: function() { 
      // When the animation is complete, removes the pin from play 
      $(pinID).css({ 
       "left": -200, "top": -200 
      }); 
     } 
    }); 
} 

我想有一個左側和頂部的動畫功能,它只是模擬了一個奇怪的運動的開端。 如果有人能幫助我,我會很感激。謝謝。

編輯下面是結果(感謝ZS V):

this.animation = function (pinID) { 
    if (knockedPins.indexOf(pinID) == -1) { 
     var rdm = ((Math.random() * 10) + 1); 
     var degree; 
     var transFormOrigin; 
     if (rdm <= 5) { 
      degree = -90; 
      transFormOrigin = '0% 100%'; 
     } 
     else { 
      degree = 90; 
      transFormOrigin = '100% 100%'; 
     } 
     $(pinID).css({ "transform-origin": transFormOrigin }); 
     knockedPins.push(pinID); 

     $(pinID).animate({ deg: degree }, 
     { 
      duration: 1000, 
      step: function (now) { 
       // In the step-callback (that is fired each step of the animation), 
       // the pin will rotate to the current degree of the animation 
       $(pinID).css({ 
        transform: 'rotate(' + now + 'deg)' 
       }); 
      }, 
      complete: function() { 
       // When the animation is complete, removes the pin from play 
       $(pinID).css({ 
        "left": -200, "top": -200 
       }); 
      } 
     }); 
    } 
} 

我加入了變換origin屬性,並且必須使用一個數組來存儲那些已經被撞引腳的IDS ,否則它會動搖,直到它休息。嘿嘿

+0

如果,例如,要模擬有人滑倒您可能需要平移和旋轉相結合。 – cst1992

+0

嘿,謝謝。但這並不是必要的,因爲我不想做出「滑溜溜」的效果(也許我自己解釋不好),而是將div旋轉到特定點而不是中間旋轉,這是旋轉的缺點。如果您想查看我的意思,我使用代碼詳細信息編輯了帖子。再次感謝。 :) – taiko

+0

不,我知道,我只是舉了一個例子。 – cst1992

回答

1

你必須圍繞它的角落,而不是中心旋轉對象(圖片)。這是一個討論如何做到這一點:https://stackoverflow.com/a/6633676/6624619

+0

這正是我需要的。謝謝。我也做了一些修改,以確保它只會運行一次函數(因爲是隨機的,因爲它會影響transform-origin屬性)。我用詳細的代碼編輯了帖子。再次感謝! :) – taiko