SFML community forums

Help => General => Topic started by: jmaslaki on March 13, 2014, 03:23:16 am

Title: How can you toggle something with pressing a key?
Post by: jmaslaki on March 13, 2014, 03:23:16 am
I looked in the resources, I couldn't find any information on how to do this. So I'm trying to figure out how to set "int a" from 0 to 1 by pressing down a key. For example:

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)){
a = 1; //int a was already declared
}

So the problem here is that a = 1 as long as the key is pressed down, but once I release it, it goes back to equaling 0. I want to press it, and have it stay 1(not from releasing, from pressing once). Any solutions? Thanks.

EDIT: Forgot to mention this is in while (window.isOpen()){}
Title: Re: How can you toggle something with pressing a key?
Post by: AlejandroCoria on March 13, 2014, 03:45:06 am
Maybe you have a = 0 in the same loop.

In what way are you checking the value of a?

You can put the code here, it will be much easier to see the error.
Title: AW: How can you toggle something with pressing a key?
Post by: eXpl0it3r on March 13, 2014, 07:53:33 am
The easiest way would be to use event and change it to 1 when keypressed is triggered and to 0 if keyrelease is triggere.

If you're just interested in 0 and 1, which could be represented as boolean, theb you could use sf::Keyboard::isKeyPressed() directly, since that returns true if pressed, false otherwise. ;)
Title: Re: How can you toggle something with pressing a key?
Post by: didii on March 13, 2014, 08:05:27 am
You need to declare a default value for a before your loop starts. This way it's not destroyed after the loop restarts. After setting the variable to a=1 it will thus stay at 1 until you change it again.

If you need an on/off toggle, it's easier, cleaner and more efficient to use a bool. Then you can simply write
bool a = ...;
while (...) {
    if (keypressed)
        a = !a;
}
If you have more than 2 toggles, a clean way to write it could be
int a = ...;
while (...) {
    if (keypressed)
        a = (a+1)%N;
}
where N is the number of states and % is the modulus operator.


The easiest way would be to use event and change it to 1 when keypressed is triggered and to 0 if keyrelease is triggere.

If you're just interested in 0 and 1, which could be represented as boolean, theb you could use sf::Keyboard::isKeyPressed() directly, since that returns true if pressed, false otherwise. ;)
I think you are misinterpreting. He meant to toggle a value only when a key is pressed, when released it should stay that value. But it is indeed safer to use events rather than real-time input in case of a toggle.