Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I wonder if there is a simple way to use some kind om interval timing in XNA? For example call a method every 10 seconds?

I'm also wondering if there is a way to hide and unhide a sprite when it's on the screen?

Thanks!

share|improve this question
add comment

2 Answers

up vote 4 down vote accepted

Question 1:

To expand on Jason's answer, I typically handle it by creating a couple variables:

float timer = 10;         //Initialize a 10 second timer
const float TIMER = 10;

Then in the Update() method, you can then do something like this:

public void Update(GameTime gameTime)
{
    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
    timer -= elapsed;
    if (timer < 0)
    {
        //Timer expired, execute action
        timer = TIMER;   //Reset Timer
    }
}

Question 2:

Create a variable:

bool drawSprite = true;

Set this variable in your code, depending on where you want to switch it on or off. You could set it inside of your timer action, so it would flip on/off every 10 seconds.

if (timer < 0)
{
    drawSprite = !drawSprite;
    timer = TIMER;   //Reset Timer
}

Then in your Draw() function:

public void Draw()
{
    if (drawSprite)
        //Drawcode
}
share|improve this answer
    
Nice! This appears to be a good solution! –  3D-kreativ Jul 12 '12 at 21:53
    
ElapsedGameTime is the time elapsed since the last update. Hopefully, for the sake of your game's responsiveness, the TotalSeconds will always be zero for this, so the timer variable in this example will never reach zero. You may need to use ElapsedGameTime.TotalMilliseconds/1000 instead. Or use the whole TimeSpan struct as Jason implicitly suggests. –  indeed005 Jul 13 '12 at 1:24
    
Hmm, thanks for the advice, but none of the code example works! Nothing happens after 10 sec! –  3D-kreativ Jul 13 '12 at 8:49
    
It only works with this code: if (timer < 1) –  3D-kreativ Jul 13 '12 at 8:58
    
Yes, the original code was checking the float against zero, which is very wrong. Modified it to check if < 0 –  Jon Jul 13 '12 at 10:58
show 1 more comment

You could have a timer variable, and add gameTime.ElapsedGameTime to it on every update().

As for your second question: in your draw() function, use an if statement for drawing sprites.

share|improve this answer
    
Thanks! But it had been easier to understand with some code example –  3D-kreativ Jul 12 '12 at 21:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.