如何在SDL中定期调用函数?

时间:2013-01-04 21:43:51

标签: c++ timer sdl intervals

我需要跟踪时间间隔,并在每次间隔过去时调用一个函数。我已经在SDL_AddTimer上查阅了SDL的文档,但是gcc抱怨说我做错了。

那么,我该如何定期,或者如何使用AddTimer

SDL文档中AddTimer的示例对我来说并不清楚。 gcc告诉我,我在回调函数中缺少参数,并且我的计时器不存在于范围内(但我不知道要声明什么)。这是我疯狂尝试过的:

SDL_AddTimer(3000,changeMusic,NULL);
Uint32 changeMusic(Uint32 interval, void *param){...

我想也许如果经过的时间可以被3秒整除,那么函数会运行,但最终以不稳定的频率激活。

if(interval.getTicks()%3000==0){
    changeMusic();
}

或者,如果倒计时为零,重置它并调用一个函数,但我不知道如何使计时器倒计时。

//something like this
cdTimer=(3000 to 0)
if(cdTimer==0){
    cdTimer=(3000 to 0);
    changeMusic();
}

1 个答案:

答案 0 :(得分:3)

我很确定,从您的代码片段开始,您在调用SDL_AddTimer()之前没有声明该函数,因此编译器认为它是错误的函数参数。

有两种解决方案:

  1. 在定时器调用之前将回调函数从SDL_AddTimer()移动到某处。
  2. 使用前向声明来移动该功能。
  3. 您也可能尝试在类中使用成员函数,在这种情况下,它必须是静态成员函数。像这样:

    class Mylene
    {
     public:
        ... // other stuff goes here ... 
        static Uint32 ChangeMusic(Uint32 x, void *p)
        {
             Mylene *self = reinterpret_cast<Mylene *>(p);
             self->doChangeMusic();
             return 0;
        }
    
        ... more stuff here, perhaps ... 
    };
    
    
    Mylene mylene(...);  // Note, must not go out of scope before the ChangeMusic is called. 
    // ... stuff ... 
    timer_id = SDL_AddTimer(3000, &Mylene::ChangeMusic, &mylene);   // Passing the mylene object... 
    
    ... Do other things here for some time ...