Hello guys, I am still working on my first SFML game and I have another question for you today.This time I have a problem with the keyboard.
My code looks something like this:
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left) || sf::Keyboard::isKeyPressed(sf::Keyboard::A))
//Move Left
It works as supposed, the object moves to left, but it also works when I'm outside of the render window. For example if I leave the game open and go write some text somewhere, every time I use "ASDW" the object moves. It's like sensing the keys globally.
Well since I test if the key is pressed, this make total sense (the game sits back and tests if keys are pressed).
Is there any better way of doing this?
Well, you should use something like this:
int main()
{
bool isPaused = false;
//[CODING] Here is probably your window coding.
while (window.isOpen())
{
while (window.pollEvent(event))
{
if (event.type == sf::Event::LostFocus)
isPaused = true;
else if (event.type == sf::Event::GainedFocus)
isPaused = false;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left) && !isPaused)
{
//move left
}
}
return 0;
}
I hope it helps