[英]How to create a timer/counter in C# XNA
我是C#编程的新手,这是我第一次在XNA中使用它。 我正在尝试与朋友一起制作游戏,但我们正在努力制作一个基本的计数器/时钟。 我们需要的是一个定时器,从1开始,每2秒+1,最大容量为50.任何编码帮助都会很棒! 谢谢。
要在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
}
我不是C#或XNA的专家,所以我感谢任何提示/建议。
如果您不想使用XNA ElapsedTime,可以使用c#计时器。 你可以找到关于它的教程,这里是定时器的msdn参考
无论如何,这里有一些代码可以或多或少地做你想要的。
首先,你需要在你的班级中声明这样的东西:
Timer lTimer = new Timer();
uint lTicks = 0;
static uint MAX_TICKS = 50;
然后你需要在你想要的时候启动计时器
private void InitTimer()
{
lTimer = new Timer();
lTimer.Interval = 2000;
lTimer.Tick += new EventHandler(Timer_Tick);
lTimer.Start();
}
然后在Tick事件处理程序中,您应该每50个刻度执行任何您想要执行的操作。
void Timer_Tick(object sender, EventArgs e)
{
lTicks++;
if (lTicks <= MAX_TICKS)
{
//do whatever you want to do
}
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.