How to create a timer/counter in C# XNA

给你一囗甜甜゛ 提交于 2021-01-29 08:11:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!