Motion without frame rate limit C ++ SFML

Now I am working on creating a game in SFML, but I am fixated on movement without limiting the frame rate. Right now, when I figured out how to achieve a consistent frame rate on all computers, use

window.setFramerateLimit(30); 

I want to find a way to not have a frame rate limit so that it looks better on the best computers and therefore, if someone has a really slow computer, they can still play the game. What would be the best way to do this.

+4
source share
2 answers

You need to transfer the time elapsed since the last frame to the object that you want to draw, and then calculate the space that the object should move, for example:

 sf::Clock clock; int speed = 300; //Draw func that should be looped void Draw() { sf::Time elapsedTime = clock.restart(); float tempSpeed = elapsedTime.asSeconds() * speed; drawnObject.move(tempSpeed, 0); drawnObject.draw(window); } 

Thus, "drawObject" will move 300 (pixels?) Per second to the right, regardless of FPS

+6
source

@Waty's answer is correct, but you can use a fixed time step.

Take a look at the source code for the SFML developer book . Here's an interesting snippet :

 const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f); // ... sf::Clock clock; sf::Time timeSinceLastUpdate = sf::Time::Zero; while (mWindow.isOpen()) { sf::Time elapsedTime = clock.restart(); timeSinceLastUpdate += elapsedTime; while (timeSinceLastUpdate > TimePerFrame) { timeSinceLastUpdate -= TimePerFrame; processEvents(); update(TimePerFrame); } updateStatistics(elapsedTime); render(); } 
+4
source

Source: https://habr.com/ru/post/1497725/


All Articles