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

2 回答 2

2

如果问题只是循环问题,您只需删除更新中导致其循环的代码位(即if (CurrentFrame++ == numberOfFrames - 1) CurrentFrame = 0;)您需要做的就是让动画再次播放,将当前帧设置回 0当你想要它播放时。(要停止绘制,只需在需要时进行绘制调用。)

如果您正在寻找一种构建它的方法(这就是我最初解释您的问题的方式!)为什么不使用您想要动画的任何对象设置一个 Animated 类。类似的东西

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

显然,您可以将其扩展为更复杂(例如,使用您的计时器来选择何时移动帧等。

于 2013-03-30T23:37:33.877 回答
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);
}
于 2013-03-30T23:32:59.987 回答