1

在我的乒乓球比赛中,我正在制作我有两个桨和一个球。我正在尝试这样做,当球与桨碰撞时,会显示效果/动画。我有一个 spritehseet 和一个工作动画。我用它来检测动画何时播放(请注意,我还没有固定效果的位置,所以它在 400、300 上播放只是为了看看它是否有效)

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

现在它在碰撞时出现,但只持续很短的毫秒,因为当球离开桨时,它就消失了。我知道它被编码为仅在与桨碰撞时出现,但是我可以通过什么方式使其仅在动画结束时才消失?

4

1 回答 1

1

You can easily used elapsed time and some makeshift timers to do this. I assume your spritesheet is a series of frames, and that you already have rendering set up.

You will need some variables to start out:

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.

In your update method you need to

  1. Check if the ball is intersecting, and set IsPlaying to true
  2. If the animation IsPlaying, increment the frameTimePlayed by the elapsed time
  3. If the frameTimePlayed is equal to or greater than the animationTime, stop the animation by setting IsPlaying to false

In your draw method you need to

  1. Draw the animation, if IsPlaying

Here is some example code:

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

And for drawing, pretty easy, just check is IsPlaying and draw if that is the case.

I made sure to comment the code good, so hopefully this will help you understand and work better.

You could also use a double and use TotalSeconds instead of milliseconds if needed, and calculate elapsed time with float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

于 2013-07-28T23:13:24.633 回答