当我按下一个键时,我怎样才能在几秒钟内制作一个方法

本文关键字:几秒 钟内制 方法 一个 下一个 | 更新日期: 2023-09-27 18:36:30

我想在按下某个键后的 2 秒内制作动画。例如,我想加载一个动画进行拍摄,我希望它只需要 2 秒钟,然后它会转回"停留"动画。

class Player
{
PlayerAnimation animation;
Animation walk;
Animation stay;
Animation jump;;
public Vector2 position;
public Vector2 velocity;
public Rectangle rect;
public bool jumping = false;
public int health = 5;
public Vector2 Position{ get { return position; } }

public Player() { }
public void Load(ContentManager Content) {
    walk = new Animation(Content.Load<Texture2D>("walk"), 46, 0.1f, true, rect);
    animazioneMinima = new Animation(Content.Load<Texture2D>("stay"),37, 0.15f, true, rect);
    jump = new Animation(Content.Load<Texture2D>("jump"), 51, 0.1f, true , rect);

}
public void Update(GameTime gameTime)
{
    position += velocity;
    rect = new Rectangle((int)position.X, (int)position.Y, 43, 46);
    Input(gameTime);

    if (velocity.X != 0)
        PlayerAnimation.PlayAnimation(walk);
    else if (velocity.X == 0)
        PlayerAnimation.PlayAnimation(stay;
    if (velocity.Y < 10)
        velocity.Y += 0.4f;
}

private void Input(GameTime gameTime)
{
    if (Keyboard.GetState().IsKeyDown(Keys.D))
        velocity.X = (float)gameTime.ElapsedGameTime.TotalMilliseconds / 3;
    else if (Keyboard.GetState().IsKeyDown(Keys.A))
        velocity.X = -(float)gameTime.ElapsedGameTime.TotalMilliseconds / 3;
    else velocity.X = 0f;

    if (Keyboard.GetState().IsKeyDown(Keys.Space) && jumping == false)
    {
        position.Y -= 5f;
        velocity.Y = -9f;
        jumping = true;
    }
}

public void Draw(GameTime gameTime, SpriteBatch spriteBatch)
{
    SpriteEffects rotate = SpriteEffects.None;
    if (velocity.X >= 0)
        rotate = SpriteEffects.None;
    else if (velocity.X < 0)
        rotate = SpriteEffects.FlipHorizontally;
    PlayerAnimation.Draw(gameTime, spriteBatch, position, rotate);
}
}
}

当我按下一个键时,我怎样才能在几秒钟内制作一个方法

您可以使用

通过方法参数传递给您的GameTime,常见的解决方案是"保存"起始GameTime,并且每个游戏循环迭代检查差异:

private GameTime animGameTimeStart;
public void Update(GameTime gameTime)
{
    //When starting the animation:
    this.animGameTimeStart = gameTime;
    if(gameTime.ElapsedTime - animGameTimeStart.ElapsedTime <= TimeSpan.FromSeconds(2))
    { 
        //Set again to Idle
    }
}