Hey, I've been playing around with trying to make a game in my spare time. I've unfortunately just realized that my game loop is just terrible after five seconds of execution, and I'm not sure what to do to fix it. I've been following gaffer's game loop tutorial, for what it's worth. If you compile the below code, you'll see that initially everything is fine, but eventually the time becomes "jerky," and then everything just stops.
I know that this is (likely) due to a poor game loop, specifically the use of floats to store the time. But I don't know exactly what I'm doing wrong. I provided an attempted minimal example of my problem.
On a slightly related note, if there's something fundamentally wrong with my game loop structure, or I'm using poor coding practices somewhere, please let me know! Thanks!
#include <SFML/Graphics.hpp>
void update(sf::CircleShape & s , float t ,float dt){
s.setPosition(250+(float)(50*std::sin(t/10000.0)),250+(float)(50*std::cos(t/10000.0)));
}
int main(){
sf::RenderWindow window(sf::VideoMode(500,500),"Testing!");
sf::Clock clock;
clock.restart();
sf::CircleShape s;
s.setRadius(50);
s.setFillColor(sf::Color::Red);
float t = 0.0f;
const float dt = 0.01f;
float currentTime = clock.getElapsedTime().asSeconds();
float accumulatedTime = 0.0f;
//Window Loop
while(window.isOpen()){
//Event processing.
sf::Event event;
while (window.pollEvent(event)){
if (event.type == sf::Event::Closed)
window.close();
}
//Timestep Updating.
float newTime = clock.getElapsedTime().asSeconds();
float frameTime = newTime - currentTime;
if(frameTime > 0.25)
frameTime = 0.25;
currentTime = newTime;
accumulatedTime+=newTime;
//Update loop.
while(accumulatedTime > dt){
update(s,t,dt);
accumulatedTime-=dt;
t+=dt;
}
//Draw items, Linear interpolation.
const float alpha = accumulatedTime / dt;
window.clear(sf::Color::Black);
window.draw(s);
window.display();
}
}