问题
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.
回答1:
To create a timer in XNA you could use something like this:
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.
回答2:
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
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.
void Timer_Tick(object sender, EventArgs e)
{
lTicks++;
if (lTicks <= MAX_TICKS)
{
//do whatever you want to do
}
}
Hope, this helps.
来源:https://stackoverflow.com/questions/13394892/how-to-create-a-timer-counter-in-c-sharp-xna