Search code examples
c++sfmlgame-loop

How to slow down my program and getting user input?


To get user input with SFML I use this function

char SFMLDisplayManager::handleEvents()
{
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Z))
    return ('z');
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
    return ('s');
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q))
    return ('q');
  if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
    return ('d');
  return (0);
}

Then, to slow down my program, I use

sf::sleep((sf::milliseconds(150)));

This works fine but when I press a key quickly, sometimes I don't get the input. I suppose this happens because I press they key during the sleep.

But I don't know how to solve this.

Have an idea ? Thanks


Solution

  • Reduce the sleep time.

    If you have the program in while loop without sleep it does take 100% of your cpu time, but setting the sleep value to just 1ms will make it use it about 0%.

    EDIT

    Generally it is a good idea to have the logic loop separated from the drawing loop(calling the logic loop only every n ms), or computing everything in the game based on the delta time (the time that has passed from the last frame).

    You can read more about game loops and sfml here https://github.com/SFML/SFML/wiki/Tutorial:-Basic-Game-Engine#gameloop