首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >单人游戏C#定时器(每3秒做一次15秒)

单人游戏C#定时器(每3秒做一次15秒)
EN

Stack Overflow用户
提问于 2019-05-24 21:25:48
回答 5查看 1.7K关注 0票数 1

我正在尝试创建一个计时器,例如,在15秒内每隔3秒执行一个动作。

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

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

代码语言:javascript
运行
复制
public override Stats Attack()
{        
    attack = true;
    return new Stats(0, -stats.Damage, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
代码语言:javascript
运行
复制
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);
}
EN

回答 5

Stack Overflow用户

发布于 2019-05-24 23:48:26

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

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

首先,你需要检查怪物是否真的击中了播放器(如果检测到碰撞):

代码语言:javascript
运行
复制
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类中,您需要:

代码语言:javascript
运行
复制
public float ModifierDuration {
 get {
  return modifierDuration;
 }
 set {
  modifierDuration = value;
  modiferCurrentTime = 0;
 }
}

然后在Player类的Update方法中:

代码语言:javascript
运行
复制
// 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
}

希望这能有所帮助!

票数 2
EN

Stack Overflow用户

发布于 2019-05-24 23:22:48

您需要存储开始时间,或上次执行操作的时间。然后,在每次更新期间,将经过的时间与存储的时间进行比较。如果3秒已过,则执行该操作,存储当前时间并重复该过程。

票数 0
EN

Stack Overflow用户

发布于 2019-05-25 00:34:26

我不知道单人游戏,但如果我在C#应用程序中执行此操作,我会使用计时器,并传入计时器需要修改的任何内容。

这里有很好的信息,https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8和我从这里偷了一些代码,并以此为例进行了修改,以证明我的想法。我扩展了System.Timer,允许它运行一段时间并自动停止。您可以设置频率和持续时间,然后忘记它。假设您能够从计时器更新此信息。

代码语言:javascript
运行
复制
class Program
{
    private static FixedDurationTimer aTimer;
    static void Main(string[] args)
    {
        // Create a timer and set a two second interval.
        aTimer = new FixedDurationTimer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Start the timer
        aTimer.StartWithDuration(TimeSpan.FromSeconds(15));

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        FixedDurationTimer timer = source as FixedDurationTimer;

        if (timer.Enabled)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
    }

    public class FixedDurationTimer : System.Timers.Timer
    {
        public TimeSpan Duration { get; set; }
        private Stopwatch _stopwatch;


        public void StartWithDuration(TimeSpan duration)
        {
            Duration = duration;
            _stopwatch = new Stopwatch();
            Start();
            _stopwatch.Start();
        }

        public FixedDurationTimer()
        {
            Elapsed += StopWhenDurationIsReached;
        }

        private void StopWhenDurationIsReached(object sender, ElapsedEventArgs e)
        {
            if (_stopwatch != null && Duration != null)
            {
                if (_stopwatch.Elapsed > Duration)
                {
                    Console.WriteLine("Duration has been met, stopping");
                    Stop();
                }
            }
        }
    }
}

您可以在这里看到如何将对象传递到计时器中的示例(@JaredPar的示例) How do I pass an object into a timer event?

代码语言:javascript
运行
复制
string theString = ...;
timer.Elapsed += (sender, e) => MyElapsedMethod(sender, e, theString);

static void MyElapsedMethod(object sender, ElapsedEventArgs e, string theString) {
...
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56293634

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档