Anthony T.
Hi,
I’m havign a bit of trouble with this, no matter ho I try to do it…
I have a game, in which I have the following (just an example):
class Stage1System {
private:
SDL_TimerID MoveTimer;
Uint32 MoveFunc(Uint32, void*);
… and yadda yadda yadda …
}
Stage1System::Stage1System() {
SDL_AddTimer(50, ???, NULL);
}
Now obviously MoveFunc is the function I want the timer to call.
But I can’t
seem to figure out how to get SDL_AddTimer to work with a member function,
private or public. Can someone point me in the right direction? I
can get it
to work on non-member functions no problem, but I need it to
access private members of the class.
Yes, this can be done, but it takes a little fiddling first. The main
problem is that if you wanna point to a member function, you need a pointer
to the object itself (or make the member static). Luckily, though, you can
send along a pointer to the timer callback function. This pointer can point
to an object that contains the object’s this-pointer and the member function
pointer. You then dereference the pointer to the object, get the object and
function pointer, and make the call.
You’re in luck too, because I just wrote up a short article about just such
an object. It’ll probably go on gamedev.net eventually, but here’s a
pre-release:
http://www.thecodezone.com/caller.htm
And here’s a class encapsulating the SDL timer that uses this object. Just
wrote it yesterday:
class Timer
{
public:
Timer(const Uint32 &rInterval, const Caller &rCallback, void
*pPointer=NULL) : MyInterval(rInterval), MyCaller(rCallback), MyID(NULL),
pMyPointer(pPointer) { }
~Timer() { Stop(); }
void Start() { MyID = SDL_AddTimer(MyInterval, TimerCallback,
this); }
void Stop() { if (MyID) { SDL_RemoveTimer(MyID); MyID = NULL; } }
private:
SDL_TimerID MyID;
Caller MyCaller;
Uint32 MyInterval;
void *pMyPointer;
static Uint32 TimerCallback(Uint32 i, void *pParam) { ((Timer
*)pParam)->MyCaller.Call(((Timer *)pParam)->pMyPointer); return i; }
};
I wanna make the caller object in the article into a template, but I’m not
strong enough with templates yet. Maybe someday :)> From: sdl-admin at libsdl.org [mailto:sdl-admin at libsdl.org]On Behalf Of
Sent: Friday, April 12, 2002 11:46 AM
To: sdl at libsdl.org
Subject: [SDL] Timer inside of a class
John Hattan Sweet software for a saturnine world
@John_Hattan http://www.thecodezone.com