首页 > 解决方案 > Monogame C# Timer(每 3 秒做 15 秒)

问题描述

我正在尝试创建一个计时器,例如,在例如 15 秒期间每 3 秒执行一次操作。

我尝试使用 gameTime.ElapsedGameTime.TotalSeconds 和循环,但不幸的是它不起作用。

我有一个 Attack() 函数,可以在敌人攻击它时减少玩家统计数据。我希望在一个特定的敌人的情况下,这个函数在指定的时间段内会减去玩家的生命值,例如每 3 秒。我想应该在更新函数中访问gameTime,不幸的是,我不知道该怎么做。

public override Stats Attack()
{        
    attack = true;
    return new Stats(0, -stats.Damage, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
public override void Update(GameTime gameTime)
{
    spriteDirection = Vector2.Zero;                                 // reset input
    Move(Direction);                                                // gets the state of my keyborad

    float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds; // make movement framerate independant

    spriteDirection *= Speed;                                       // add hero's speed to movement 
    position += (spriteDirection * deltaTime);                      // adding deltaTime to stabilize movement
    totalPosition = new Vector2((int)((BottomBoundingBox.Center.X) / 32.0f), (int)((BottomBoundingBox.Center.Y) / 32.0f));

    base.Update(gameTime);
}

标签: c#monogame

解决方案


我会让它变得简单,所以你需要修改我的代码来达到你想要的结果。

我最好的猜测是,当你的怪物击中你的玩家时,你想有一个特殊的效果。

首先,您需要检查怪物是否真的撞到了玩家(如果检测到碰撞):

if (collision)//if it's true
{
// Apply your special effect if it is better than
   // the one currently affecting the target :
   if (player.PoisonModifier <= poisonModifier) {
    player.PoisonModifier = poisonModifier;
    player.ModifierDuration = modifierDuration;
   }

   //player.setColor(Color.Blue);//change color to blue
   player.hitPoints -= Poision.Damage;//or enemy.PoisonDamage or whatever you define here
   hit.Expire();//this can be for the arrow or bullet from your enemy or simply just a normal hit
}

在你的Player课堂上,你需要:

public float ModifierDuration {
 get {
  return modifierDuration;
 }
 set {
  modifierDuration = value;
  modiferCurrentTime = 0;
 }
}

然后在类的Update方法中Player

// If the modifier has finished,
if (modiferCurrentTime > modifierDuration) {
 // reset the modifier.  
 //stop losing HP code is here   
 modiferCurrentTime = 0;//set the time to zero
 setColor(Color.White);//set back the color of your player
}

count += gameTime.ElapsedGameTime.TotalSeconds;//timer for actions every 3s

if (posionModifier != 0 && modiferCurrentTime <= modifierDuration) {
 // Modify the hp of the enemy.
 player.setHP(player.getCurrentHP() - posionDamage);
 //Or change it to every 3s
 //if (count > 3) {
 //  count = 0;
 //DoSubtractHP(player);
 //}
 // Update the modifier timer.
 modiferCurrentTime += (float) gameTime.ElapsedGameTime.TotalSeconds;
 setColor(Color.Blue);//change the color to match the special effect
}

希望这可以帮助!


推荐阅读