SFML community forums

Help => General => Topic started by: Flaze07 on April 06, 2018, 04:03:24 pm

Title: Using Events to check for inputs ?
Post by: Flaze07 on April 06, 2018, 04:03:24 pm
Should I use Events to check for inputs to i.e move my character or should I use the other one ??

i.e
Code: [Select]
        sf::Event event;
        while (win.pollEvent(event))
        {
            if (event.type == sf::Event::KeyPressed)
            {
                if (event.key.code == sf::Keyboard::Space) chara.jump();
            }
        }

or

Code: [Select]
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) chara.jump();

which one is better?
Title: Re: Using Events to check for inputs ?
Post by: eXpl0it3r on April 06, 2018, 04:10:35 pm
Both work, neither is objective better or worse. Pick the one you're more comfortable with writing code for.
Title: Re: Using Events to check for inputs ?
Post by: Flaze07 on April 06, 2018, 04:59:06 pm
Got it, also is it better to
sf::Event event;
        while (win.pollEvent(event))
        {
            if (event.type == sf::Event::KeyPressed)
            {
                if (event.key.code == sf::Keyboard::Space) chara.jump();
            }
        }
 

or

sf::Event event;
        if (win.pollEvent(event))
        {
            if (event.type == sf::Event::KeyPressed)
            {
                if (event.key.code == sf::Keyboard::Space) chara.jump();
            }
        }
 
Title: Re: Using Events to check for inputs ?
Post by: eXpl0it3r on April 06, 2018, 05:07:22 pm
You need to use while for the event loop. Check the official tutorial.
Title: Re: Using Events to check for inputs ?
Post by: Laurent on April 06, 2018, 05:46:31 pm
Quote
Should I use Events to check for inputs to i.e move my character or should I use the other one ??
They are not equivalent. The KeyPressed event happens once when you press the key, whereas isKeyPressed will return true as long as the key is down, ie continuously for a short while. So in the first case your character will jump once, in the second one it will restart its jump continuously until you release the key. It's easy to workaround (do nothing if a jump is already active), but from a design point of view what you need is an event.
Title: Re: Using Events to check for inputs ?
Post by: Flaze07 on April 07, 2018, 05:16:00 am
Yeah, thanks Laurent.
Also if I used while wouldn't that means that when I have an input the whole other section of the program that does some stuff wouldn't run and my program would be stuck at the input section ?