Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: sf::Event::MouseButtonReleased fires twice  (Read 798 times)

0 Members and 1 Guest are viewing this topic.

Circlify

  • Newbie
  • *
  • Posts: 1
    • View Profile
sf::Event::MouseButtonReleased fires twice
« 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();

               
        }
}

kojack

  • Full Member
  • ***
  • Posts: 170
    • View Profile
Re: sf::Event::MouseButtonReleased fires twice
« Reply #1 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";
                        }