【问题标题】:SFML mouse button released is spammingSFML 鼠标按钮释放是垃圾邮件
【发布时间】:2014-10-06 20:35:29
【问题描述】:

我正在使用 SFML 和 C++,但遇到了一个奇怪的问题,

这是我的主要游戏更新方法

while (renderService.Window.isOpen())
{
    //Poll events
    sf::Event event;
    while (renderService.Window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            renderService.Window.close();
        running = false;
    }

    MouseMovment(event);
    MouseClick(event);
    Update();
    Draw();
}

这是我的 MouseClick 方法

void Game::MouseClick(sf::Event event)
{
sf::Vector2i position = sf::Mouse::getPosition(renderService.Window);

    if (event.mouseButton.button == sf::Mouse::Left && event.type == sf::Event::MouseButtonReleased)
    {
        std::cout << "Mouse released" << std::endl;
    }
}

现在这是奇怪的部分,在我的控制台中,有时我的 cout 会被发送 10/20 次垃圾邮件,但有时它会完美运行,我是否错误地调用了该事件?

【问题讨论】:

    标签: c++ sfml


    【解决方案1】:

    你做错了,假设触发了 MouseButtonReleased 事件并且你的轮询函数抓住了它(跟随 cmets 中的数字):

    while (renderService.Window.isOpen()) // 4) The loop starts again
    {
        //Poll events
        sf::Event event; 
        while (renderService.Window.pollEvent(event)) // 1) Grabs the event // 5) No more events
        {
            if (event.type == sf::Event::Closed) // 2) Nope, it's not this one
                renderService.Window.close();
            running = false;
        }
    
        MouseMovment(event);
        MouseClick(event); // 3) Yes, handle it // 6) Uses the unmodified event variable - undefined behavior
        Update();
        Draw();
    }
    

    你应该这样做:

    sf::Event event;
    
    // while there are pending events...
    while (window.pollEvent(event))
    {
        // check the type of the event...
        switch (event.type)
        {
            // window closed
            case sf::Event::Closed:
                ...
                break;
    
            // mouse button released
            case sf::Event::MouseButtonReleased:
            {
               if (event.mouseButton.button == sf::Mouse::Left)
                ...
            } break;
    
            // we don't process other types of events
            default:
                break;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      相关资源
      最近更新 更多