SFML community forums

Help => Window => Topic started by: Circlify on April 12, 2022, 07:32:29 pm

Title: sf::Event::MouseButtonReleased fires twice
Post by: Circlify on April 12, 2022, 07:32:29 pm
Hello! I noticed that, for whatever reason, sf::Event::MouseButtonReleased was firing twice (once when a mouse button was pressed and once when it was released). Why is this happening? I have shortened my code to this small snippet that causes the issue:

#include <iostream>
#include <SFML/Graphics.hpp>

int main() {
        sf::RenderWindow win(sf::VideoMode(800, 800), "window");

        while (win.isOpen()) {
                sf::Event e;
                while (win.pollEvent(e)) {
                        switch (e.type) {
                        case sf::Event::Closed:
                                win.close();
                        case sf::Event::MouseButtonPressed:
                                std::cout << "mouse button pressed\n";
                        case sf::Event::MouseButtonReleased:
                                std::cout << "mouse button released\n";
                        }
                }
                win.clear();
                win.display();

               
        }
}
Title: Re: sf::Event::MouseButtonReleased fires twice
Post by: kojack on April 12, 2022, 08:08:49 pm
When a switch statement jumps to the matching case, it runs that code and then continues (over all following cases) until it either reaches the ending brace of the switch, or it hits a break keyword.
So when MouseButtonPressed is detected, the MouseButtonReleased will also run because it's next in line.

Change the code to:
                      switch (e.type) {
                        case sf::Event::Closed:
                                win.close();
                                break;
                        case sf::Event::MouseButtonPressed:
                                std::cout << "mouse button pressed\n";
                                break;
                        case sf::Event::MouseButtonReleased:
                                std::cout << "mouse button released\n";
                        }