user3138585
user3138585

Reputation:

How To Create And Display A Timer In XNA Game Studio

I am creating a Board-Game style game in XNA Game Studio. One of the "mini-games" inside of it requires a timer. I have tried various methods but, I am stumped. If anyone can help, I would also like it to be activated by a button. This is the code I have currently:

if (orbStart)
{
    int counter = 10;
    int limit = 50;
    float countDuration = 2f; //every  2s.
    float currentTime = 0f;
    currentTime += (float)gameTime.ElapsedGameTime.TotalSeconds; 

    if (currentTime >= countDuration)
    {
        counter++;
        currentTime -= countDuration;    
    }

    if (counter >= limit)
    {
        //Stuff
    }

    }
}

OrbStart being the boolean activated by the button. Any help will be great!

Upvotes: 0

Views: 2116

Answers (1)

Michał Żołnieruk
Michał Żołnieruk

Reputation: 2105

Okay, first create global variables, for example:

bool isTimerOn = false;
float counter = 10; // 10 seconds

Then you should change isTimerOn to true when user presses your button, hope you know how to do it. Next step- inside your update method, substract elapsed time from the last tick from counter's value and check whether the time is up:

if (isTimerOn)
{
   counter -= gameTime.ElapsedGameTime.Seconds;
   if (counter <= 0)
   doSomething();
}

Oh, I've noticed you wanted help with your button too. So first of all, you should create a Recentagle inside which your button will be placed:

Rectangle button = new Rectangle(50, 60, 100, 30);

This code means your buttons upper left point is located at (50, 60), it's width is 100 and it's height is 30. You can really read how to drawsprite at this location everywhere, as it was discussed for a couple of times here. To check whether user clicks our button, just read about how to handle gestures and check whether tap's position is inside our rectangle, here's the code:

while (TouchPanel.IsGestureAvailable)
{
   GestureSample gs = TouchPanel.ReadGesture();
   switch (gs.GestureType)
   {
     case GestureType.Tap:
       if (button.Contains((int) gs.Position.X, (int) gs.Position.Y))
          isTimerOn = true;
     break;
   }
}

To make it work there's just one more thing- you have to enable tap gesture. Inside LoadContent() method add:

TouchPanel.EnabledGestures = GestureType.Tap;

Upvotes: 1

Related Questions