Check mouse wheel state SFML

8.4k views Asked by At

In my program I wish to be able to know if the mouse wheel has been scrolled, and if so how much in what direction. Is this possible with C++ and SFML?

So far I have this:

if (sf::Event::MouseWheelEvent().delta != 0)
{
    SimulationView.zoom(1 + (10 / sf::Event::MouseWheelEvent().delta));
}

But the second line never exicutes, even when I scroll the mouse wheel

1

There are 1 answers

2
Galik On BEST ANSWER

You can read the mouse wheel as part of the event loop that is polled once per frame:

int main()
{
    sf::RenderWindow window(sf::VideoMode(320, 256), "Title");

    sf::Event event;
    while(window.isOpen())
    {
        while(window.pollEvent(event))
        {
            if(event.type == sf::Event::Closed)
                window.close();
            else if(event.type == sf::Event::MouseWheelMoved)
            {
                // display number of ticks mouse wheel has moved
                std::cout << event.mouseWheel.delta << '\n';
            }
        }

        window.clear();

        // draw window here

        window.display();
    }
}

Note: For SFML 2.3

Thanks to @Hiura for pointing out that sf::Event::MouseWheelMoved is deprecated in SFML 2.3.

Use this instead:

if(event.type == sf::Event::MouseWheelScrolled)
{
    if(event.mouseWheelScroll.wheel == sf::Mouse::VerticalWheel)
        std::cout << "wheel type: vertical" << std::endl;
    else if(event.mouseWheelScroll.wheel == sf::Mouse::HorizontalWheel)
        std::cout << "wheel type: horizontal" << std::endl;
    else
        std::cout << "wheel type: unknown" << std::endl;

    std::cout << "wheel movement: " << event.mouseWheelScroll.delta << std::endl;
    std::cout << "mouse x: " << event.mouseWheelScroll.x << std::endl;
    std::cout << "mouse y: " << event.mouseWheelScroll.y << std::endl;
}