SFML community forums

Help => General => Topic started by: ozwurld on June 27, 2014, 04:39:45 pm

Title: Making sense of pong example
Post by: ozwurld on June 27, 2014, 04:39:45 pm
Hello all,

I noticed that on the examples that come with sfml 2.0 , when a key event is been coded for the following line is used:
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Space))
{
}
 

What is the significant of this part, it doesnt look like its doing anything to me since the game still runs if i remove it, so am guessing the must be a reason its there.

(event.type == sf::Event::KeyPressed)
 

Thanks!
Title: Re: Making sense of pong example
Post by: Jesper Juhl on June 27, 2014, 04:59:00 pm
In a nutshell: the contents of a sf::Event is a union (except the type). So, if you don't check the type you won't know what members are valid, and accessing members of a wrong type will lead to undefined behaviour.
It's all explained in the documentation: http://www.sfml-dev.org/documentation/2.1/classsf_1_1Event.php#details
Title: Re: Making sense of pong example
Post by: Mörkö on June 28, 2014, 06:01:04 pm
I guess it's a matter of making event organization really easy and clean. For instance, you can have one function that deals with all KeyPressed events, and another function that deals with all KeyReleased events, something like this:

while (m_window->pollEvent(event))
{
    switch (event.type)
    {
        case sf::Event::KeyPressed:
        {
            handleKeyPresses(event);
            break;
        }
        case sf::Event::KeyReleased:
        {
            handleKeyReleases(event);
            break;
        }
    }          
}

The separation of those handlers will make your code more neat.

handleKeyPresses(sf::Event& event)
{
    switch (event.key.code)
    {
        case sf::Keyboard::Space:
        {
            activateBomb;

handleKeyReleases(sf::Event& event)
{
    switch (event.key.code)
    {
        case sf::Keyboard::Space:
        {
            deactivateBomb;
Title: Re: Making sense of pong example
Post by: Jesper Juhl on June 28, 2014, 06:06:36 pm
I guess it's a matter of making event organization really easy and clean.
...
No. It is not about making code clean or neat. It is about making it correct. Accessing invalid fields of a union is undefined behaviour and you really don't want to go there.
Title: Re: Making sense of pong example
Post by: Mörkö on June 28, 2014, 06:15:43 pm
Sure, but I don't see where OP or anyone were suggesting that someone should do that.
Title: Re: Making sense of pong example
Post by: G. on June 28, 2014, 06:44:44 pm
That was precisely OP's question. :p