1

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

那么,我怎样才能定期间隔,或者我该如何使用AddTimer

AddTimer我不清楚 SDL 文档中的示例。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();
}
4

1 回答 1

3

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

有两种解决方案:

  1. 将回调函数从 SDL_AddTimer() 移动到计时器调用之前的某个位置。
  2. 使用前向声明将函数向上移动。

您也可能尝试在类中使用成员函数,在这种情况下,它必须是静态成员函数。像这样的东西:

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 ... 
于 2013-01-05T00:07:35.553 回答