Last active
December 17, 2021 06:41
-
-
Save Harshithpm/4c1215731474b177eaf61235273d5e53 to your computer and use it in GitHub Desktop.
Some code to make sure CPU consumption is low in SDL2/C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bool gameRunning = true; | |
SDL_Event event; | |
const float timeStep = 0.01f; | |
float accumulater = 0.0f; | |
float currentTime = utils::hireTimeInSeconds(); | |
while (gameRunning) { | |
int startTicks = SDL_GetTicks(); | |
float newTime = utils::hireTimeInSeconds(); | |
float frameTime = newTime - currentTime; | |
currentTime = newTime; | |
accumulater += frameTime; | |
while (accumulater >= timeStep) { | |
while (SDL_PollEvent(&event)) { | |
if (event.type == SDL_QUIT) | |
gameRunning = false; | |
} | |
accumulater -= timeStep; | |
} | |
const float alpha = accumulater / timeStep; | |
window.clear(); | |
for (Entity& e : entities) { | |
window.render(e); | |
} | |
window.display(); | |
int frameTicks = SDL_GetTicks() - startTicks; | |
if (frameTicks < 1000/window.getRefreshRate()) | |
SDL_Delay(1000/window.getRefreshRate() - frameTicks); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment