XNA-碰撞时在原地播放动画,到达最后一帧时删除

本文关键字:最后 删除 一帧 碰撞 原地 播放 动画 XNA- | 更新日期: 2023-09-27 18:25:11

在我的乒乓球比赛中,我有两个球拍和一个球。我正在努力做到,当球与球拍碰撞时,会显示一个效果/动画。我有一个精灵集和一个工作动画。我用这个来检测动画何时播放(请注意,我还没有固定效果的位置,所以它在400300上播放只是为了看看它是否有效)

public bool BallHitEffect()
    {
        if (gPaddle.gpRect.Intersects(ball.ballRect))
        {
            return true;
        }
        else { return false; }

在我的绘图中:

protected override void Draw(GameTime gameTime)
{
   spriteBatch.Begin();
   if (BallHitEffect())
   {
      animatedSprite.Draw(spriteBatch, new Vector2(400, 250));
   }
}

现在,当它碰撞时,它会出现,但只会出现很短的一毫秒,因为当球离开球拍时,它就会消失。我知道它被编码为只在与桨板碰撞时出现,但我怎么可能让它只在动画结束时消失呢?

XNA-碰撞时在原地播放动画,到达最后一帧时删除

您可以很容易地使用经过的时间和一些临时计时器来完成这项工作。我假设您的精灵表是一系列帧,并且您已经设置了渲染。

你需要一些变量才能开始:

double frameTimePlayed; //Amount of time (out of animationTime) that the animation has been playing for
bool IsPlaying; //Self-Explanitory
int frameCount; //Frames in your sprite, I'm sure you already handle this in your animation logic, but I just threw it in here
int animationTime = 1000; //For 1 second of animation.

更新方法中,您需要

  1. 检查球是否相交,并将IsPlaying设置为true
  2. 如果动画为IsPlaying,则将frameTimePlayed增加经过的时间
  3. 如果frameTimePlayed等于或大于animationTime,则通过将IsPlaying设置为false来停止动画

绘图方法中,您需要

  1. 绘制动画,如果IsPlaying

以下是一些示例代码:

protected override void Update(GameTime gameTime)
{
    //If it is not already playing and there is collision, start playing
    if (!IsPlaying && BallHitEffect)
        IsPlaying = true;
    //Increment the frameTimePlayed by the time (in milliseconds) since the last frame
    if (IsPlaying)
        frameTimePlayed += gameTime.ElapsedGameTime.TotalMilliseconds;
    //If playing and we have not exceeded the time limit
    if (IsPlaying && frameTimePlayed < animationTime)
    {
         // TODO: Add update logic here, such as animation.Update()
         // And increment your frames (Using division to figure out how many frames per second)
    }
    //If exceeded time, reset variables and stop playing
    else if (IsPlaying && frameTimePlayed >= animationTime)
    {
        frameTimePlayed = 0;
        IsPlaying = false;
        // TODO: Possibly custom animation.Stop(), depending on your animation class
    }
}

对于绘图,非常简单,只需检查是IsPlaying,然后绘制(如果是这样的话)。

我确保对代码进行了良好的评论,所以希望这将帮助您更好地理解和工作。

如果需要,您也可以使用double,使用TotalSeconds而不是毫秒,并使用float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; 计算运行时间