4
\$\begingroup\$

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!

\$\endgroup\$

2 Answers 2

6
\$\begingroup\$

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
}
\$\endgroup\$
6
  • \$\begingroup\$ Nice! This appears to be a good solution! \$\endgroup\$
    – 3D-kreativ
    Jul 12, 2012 at 21:53
  • \$\begingroup\$ 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. \$\endgroup\$
    – indeed005
    Jul 13, 2012 at 1:24
  • \$\begingroup\$ Hmm, thanks for the advice, but none of the code example works! Nothing happens after 10 sec! \$\endgroup\$
    – 3D-kreativ
    Jul 13, 2012 at 8:49
  • \$\begingroup\$ It only works with this code: if (timer < 1) \$\endgroup\$
    – 3D-kreativ
    Jul 13, 2012 at 8:58
  • \$\begingroup\$ Yes, the original code was checking the float against zero, which is very wrong. Modified it to check if < 0 \$\endgroup\$
    – jgallant
    Jul 13, 2012 at 10:58
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Thanks! But it had been easier to understand with some code example \$\endgroup\$
    – 3D-kreativ
    Jul 12, 2012 at 21:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .