I've been looking through the internet a long time now for an easy solution to a rather easy problem.
I have this function running as a thread, and what I want is quite simple. There is plenty of pseudo code around that explains how it's done, but I'm having trouble implementing this in C/C++.
What I want: I have a loop, which I want to run 20 times a second. I have done this before, but I cannot remember for the life of me.
Here is the code I have.
void* Tick::startBeating() {
mNext = clock();
mRunning = 1;
// Loop dat
while (mRunning) {
mT = clock();
while ((mT) >= mNext) {
// do updates here
std::cout << "Tick." << std::endl;
mNext = mT + SKIP_TICKS;
}
sleep(1);
}
return NULL;
}
This doesn't work, nothing seems to work. A simple solution in C is no where to be found on the internet, and that surprises me.
Yes, I know about CLOCKS_PER_SEC but I just don't know anymore.
Any help?
I do it like this
float mAccumulatedTime;
int mLastTime;
void Init()
{
mAccumulatedTime = 0.f;
mLastTime=clock();
}
void Tick(float DeltaTime)
{
mAccumulatedTime += DeltaTime;
while (mAccumulatedTime > FixedTimeStep)
{
DoFixedTimeStepStuff();
mAccumulatedTime -= FixedTimeStep;
}
}
void Update()
{
int CurrentTime=clock();
float DeltaTime=(CurrentTime-mLastTime)/(float)CLOCKS_PER_SEC;
Tick(DeltaTime);
mLastTime=CurrentTime;
}
You need to take care to handle NaNs and "spirals of death" appropriately, but this will be enough to get you started.