2014-10-06 48 views
1

我使用SFML和C++,我得到一個奇怪的問題,發佈SFML鼠標按鈕是垃圾郵件

這裏是我的主要遊戲更新方法

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

,這裏是我的鼠標點擊的方法

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倍,但有時它會很好地工作,我會錯誤地調用事件?

回答

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

}