发布的SFML鼠标按钮是垃圾邮件

时间:2014-10-06 20:35:29

标签: c++ sfml

我正在使用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次,但有时它会完美地运行,我是否错误地调用了这个事件?

1 个答案:

答案 0 :(得分:3)

你做错了,假设一个MouseButtonReleased事件被触发,你的轮询函数抓住了它(跟随评论中的数字):

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;
    }

}