简体   繁体   English

如何在C#XNA中创建计时器/计数器

[英]How to create a timer/counter in C# XNA

I'm fairly new to C# programming, and this is my first time using it in XNA. 我是C#编程的新手,这是我第一次在XNA中使用它。 I'm trying to create a game with a friend, but we're struggling on making a basic counter/clock. 我正在尝试与朋友一起制作游戏,但我们正在努力制作一个基本的计数器/时钟。 What we require is a timer that starts at 1, and every 2 seconds, +1, with a maximum capacity of 50. Any help with the coding would be great! 我们需要的是一个定时器,从1开始,每2秒+1,最大容量为50.任何编码帮助都会很棒! Thanks. 谢谢。

To create a timer in XNA you could use something like this: 要在XNA中创建计时器,您可以使用以下内容:

int counter = 1;
int limit = 50;
float countDuration = 2f; //every  2s.
float currentTime = 0f;

currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; //Time passed since last Update() 

if (currentTime >= countDuration)
{
    counter++;
    currentTime -= countDuration; // "use up" the time
    //any actions to perform
}
if (counter >= limit)
{
    counter = 0;//Reset the counter;
    //any actions to perform
}

I am by no means an expert on C# or XNA as well, so I appreciate any hints/suggestions. 我不是C#或XNA的专家,所以我感谢任何提示/建议。

If you don't want to use the XNA ElapsedTime you can use the c# timer. 如果您不想使用XNA ElapsedTime,可以使用c#计时器。 You can find tutorials about that, here the msdn reference for timer 你可以找到关于它的教程,这里是定时器msdn参考

Anyway here is some code that do more or less what you want. 无论如何,这里有一些代码可以或多或少地做你想要的。

First, you need to declare in your class something like that: 首先,你需要在你的班级中声明这样的东西:

    Timer lTimer = new Timer();
    uint lTicks = 0;
    static uint MAX_TICKS = 50;

Then you need to init the timer whereever you want 然后你需要在你想要的时候启动计时器

    private void InitTimer()
    {
        lTimer       = new Timer();
        lTimer.Interval = 2000; 
        lTimer.Tick += new EventHandler(Timer_Tick);
        lTimer.Start();
    }

then in the Tick eventhandler you should do whatever you want to do every 50 ticks. 然后在Tick事件处理程序中,您应该每50个刻度执行任何您想要执行的操作。

    void Timer_Tick(object sender, EventArgs e)
    {
        lTicks++;
        if (lTicks <= MAX_TICKS)
        {
            //do whatever you want to do
        }
    }

Hope, this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM