2013-03-30 36 views
0

我正在寫一個遊戲,我希望每當發生碰撞時都要運行爆炸動畫。然而,我知道如何進行動畫處理的方法是基於鍵盤輸入的。編寫該方法的最佳方法是什麼,以便在調用動畫時通過所有框架單次傳遞然後停止?動畫短序列

public void Update(GameTime gametime) 
    { 
    timer += gametime.ElapsedGameTime.Milliseconds; 
     if (timer >= msBetweenFrames) 
     { 
     timer = 0; 
     if (CurrentFrame++ == numberOfFrames - 1) 
      CurrentFrame = 0; 
      rect.X = CurrentFrame * width; 
      rect.Y = 0; 
    } 
    } 

    public void Render(SpriteBatch sb, Vector2 position, Color color) 
    { 
    sb.Draw(aniTex, position, rect, color, 0, Vector2.Zero, 2.0f, SpriteEffects.None, 0); 
} 
+0

請問您的代碼做的工作?它看起來不錯。 – Virtlink

+0

在Game1.cs的Update方法有一個調用explosionAnimatio.Update(gameTime);它運行時沒有錯誤,但是它無限循環,我希望在幀上運行一次,然後停止動畫 – phcoding

+0

這似乎是因爲你循環它(當前幀結束時,將其重置爲0) –

回答

2

如果問題僅僅是循環的問題,你可以刪除在您的更新,導致它循環的代碼位(if (CurrentFrame++ == numberOfFrames - 1) CurrentFrame = 0;)所有你需要做的就是動畫再次發揮,當您想要播放時,將當前幀設置回0。 (要停止繪製,只需要在需要時進行繪製調用。)

如果您正在尋找一種方法來構建它(這是我最初解釋您的問題的方式!),爲什麼不用動畫類你可以用任何你想要動畫的對象來設置。沿

class AnimatedObject 
{ 
    Texture2D texture; 
    Rectangle currentRectangle; 
    Rectangle frameSize; 
    int frameCount; 
    int currentFrame; 

    bool isRunning; 

    public AnimatedObject(Texture2D lTexture, Rectangle lFrameSize, int lFrameCount) 
    { 
     texture = lTexture; 
     frameSize = lFrameSize; 
     currentRectangle = lFrameSize; 
     currentFrame = 0; 
    } 

    public void Pause() 
    { 
     isRunning = false; 
    } 

    public void Resume() 
    { 
     isRunning = true; 
    } 

    public void Restart() 
    { 
     currentFrame = 0; 
     isRunning = true; 
    } 

    public void Update() 
    { 
     if(isRunning) 
     { 
      ++currentFrame; 
      if(currentFrame == frameCount) 
      { 
       currentFrame = 0; 
      } 

      currentRectangle.X = frameSize.Width * currentFrame; 
     } 
    } 

    public void Draw(SpriteBatch spriteBatch) 
    { 
     if(isRunning) 
     { 
      spriteBatch.Draw(texture, currentRectangle, Color.White); 
     } 
    } 
} 

東西線很明顯,你可以擴展這是更復雜的(例如,使用您的計時器時要選擇移動幀等

+0

這是經過深思熟慮的結構,我認爲這將有助於簡化我的代碼。感謝您提供豐富的答案。 – phcoding

1

您可以停止動畫,例如,通過在動畫完成時從遊戲中刪除具有動畫的對象。

否則,您可以在動畫完成後將currentFrame設置爲非法值(例如-1)並對其進行測試。

public void Update(GameTime gametime) 
{ 
    if (currentFrame >= 0) 
    { 
     timer += gametime.ElapsedGameTime.Milliseconds; 
     if (timer >= msBetweenFrames) 
     { 
      timer = 0; 
      currentFrame++; 
      if (currentFramr >= numberOfFrames - 1) 
       currentFrame = -1; 
      rect.X = CurrentFrame * width; 
      rect.Y = 0; 
     } 
    } 
} 

public void Render(SpriteBatch sb, Vector2 position, Color color) 
{ 
    if (currentFrame >= 0) 
     sb.Draw(aniTex, position, rect, color, 0, Vector2.Zero, 2.0f, SpriteEffects.None, 0); 
} 
+0

謝謝你的回答我發現這對你有幫助。 – phcoding