I already mentioned this in other game-related threads. As always, follow Glenn Fiedler's suggestions in the Game Physics section.
What you want to do is use the constant timestamp you get by accumulating time deltas. If you want 33 updates per second, then your constant time interval should be 1/33. You can also call it the refresh rate. You must also separate the logic of the game from rendering, since they do not belong to each other. You want to be able to use the low refresh rate when rendering as fast as the machine allows. Here is a sample code:
running = true; unsigned int t_accum=0,lt=0,ct=0; while(running){ while(SDL_PollEvent(&event)){ switch(event.type){ ... } } ct = SDL_GetTicks(); t_accum += ct - lt; lt = ct; while(t_accum >= timestep){ t += timestep; t_accum -= timestep; for(std::vector<Entity>::iterator en = entities.begin(); en != entities.end(); ++en){ integrate(en, (float)t * 0.001f, timestep); } } std::vector<Entity> tmpEntities(entities.size()); for(int i=0; i<entities.size(); ++i){ float alpha = (float)t_accum / (float)timestep; tmpEntities[i] = interpolateState(entities[i].lastState, alpha, entities[i].currentState, 1.0f - alpha); } Render(tmpEntities); }
This handles flaws as well as oversampling. If you use integer arithmetic as done here, your game physics should be close to 100% deterministic, no matter how slow or fast the machine. This is the advantage of increasing time at fixed time intervals. The state used for rendering is calculated by interpolating between the previous and current states, where the residual value inside the time accumulator is used as the interpolation coefficient. This ensures that the rendering is smooth, no matter how large the timestamp.
Mads elvheim
source share