如何在 C# XNA 中创建计时器/计数器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13394892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a timer/counter in C# XNA
提问by Jon C
I'm fairly new to C# programming, and this is my first time using it in 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! Thanks.
我对 C# 编程还很陌生,这是我第一次在 XNA 中使用它。我正在尝试与朋友一起创建游戏,但我们正在努力制作基本的计数器/时钟。我们需要的是一个计时器,它从 1 开始,每 2 秒+1,最大容量为 50。任何对编码的帮助都会很棒!谢谢。
回答by Philipp
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 方面的专家,所以我感谢任何提示/建议。
回答by Osk
If you don't want to use the XNA ElapsedTime you can use the c# timer. You can find tutorials about that, here the msdn reference for timer
如果您不想使用 XNA ElapsedTime,您可以使用 c# 计时器。你可以找到关于这个的教程,这里是计时器的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.
希望这可以帮助。

