Lazzo
Lazzo

Reputation: 23

SDL: Timers and WaitEvent

So, the main loop of my game is based on a SDL_WaitEvent type, where it waits for the user to enter new letters while trying to discover a random word. My game need this to work properly but it looks like SDL_WaitEvent stays idle until user press something. The problem is I need my timer to continuosly refresh in order for the player to keep track of it, but when the game reaches the event loop, my timer stays idle and I am not able to find a away to keep it refreshing, any tips would be very appreciated.

Summarizing:

Timer starts: 59 (seconds) . . .

It only will refresh and show the time elapsed when and IF I press something.

Upvotes: 2

Views: 3165

Answers (1)

genpfault
genpfault

Reputation: 52083

SDL_AddTimer() with a callback that uses SDL_PushEvent() to post a user message to the event queue:

/* Start the timer; the callback below will be executed after the delay */

Uint32 delay = (33 / 10) * 10;  /* To round it down to the nearest 10 ms */
SDL_TimerID my_timer_id = SDL_AddTimer(delay, my_callbackfunc, my_callback_param);

...

Uint32 my_callbackfunc(Uint32 interval, void *param)
{
    SDL_Event event;
    SDL_UserEvent userevent;

    /* In this example, our callback pushes an SDL_USEREVENT event
    into the queue, and causes our callback to be called again at the
    same interval: */

    userevent.type = SDL_USEREVENT;
    userevent.code = 0;
    userevent.data1 = NULL;
    userevent.data2 = NULL;

    event.type = SDL_USEREVENT;
    event.user = userevent;

    SDL_PushEvent(&event);
    return(interval);
}

Upvotes: 4

Related Questions