I'm trying to make my game's server thread run at a fixed 30Hz but can't figure out how. Basically, before I just had a stupid while(1) { //do everything as fast as you can} which means that for my computer, with client and server on localhost, results in sending ~30,000(!) packets per second. which of course, is way, way too much.
Which is all because it's burning as fast as it can, and since the player position is being changed extremely quickly, it will send out those packets just as quickly.
It's based off of the infamous fixed timestep: http://gafferongames.com/game-physics/fix-your-timestep/ but I'm trying to use C++11's chrono features, but anything I try to do still doesn't slow down the server. Either it won't ever run the inner while loop, or it will do so (like it does right now with the code below), super super fast-like.
The problem's definitely something simple/stupid, but I can't tell what.
Thanks.
std::chrono::system_clock::time_point currentTime = std::chrono::high_resolution_clock::now();
double accumulator = 0.0;
const double dt = (1.0 / 30.0) / 1000.0 / 1000.0; // runs at 30 hz
double t = 0.0;
while (1) {
std::chrono::system_clock::time_point newTime = std::chrono::high_resolution_clock::now();
double frameTime = std::chrono::duration_cast<std::chrono::nanoseconds>(newTime - currentTime).count();
if ( frameTime > 1.0/15.0 / 1000.0 / 1000.0) {
frameTime = 1.0/15.0 / 1000.0 / 1000.0; // note: max frame time to avoid spiral of death
}
currentTime = newTime;
accumulator += frameTime;
while ( accumulator >= dt )
{
m_world->update(dt);
poll();
t += dt;
accumulator -= dt;
}
const double alpha = accumulator / dt;
// do network shit
}