2017-04-01 43 views
0

我正在試驗SDL中的鍵盤輸入,並且遇到了一個奇怪的問題。每當我輸入僅輸出相應的反應有時(點擊X只是有時關閉該程序,按1只有時候輸出「你按1」這是我的主要代碼:SDL輸入只能工作有時

#include <iostream> 
#include <SDL.h> 

#include "Screen.h" 
#include "Input.h" 
using namespace std; 

int main(int argc, char *argv[]) { 
    Screen screen; 
    Input input; 
    if (screen.init() == false) { 
     cout << "Failure initializing SDL" << endl; 
    } 

    while (true) { 

     if (input.check_event() == "1") { 
      cout << "You pressed 1" << endl; 
     } else if (input.check_event() == "quit") { 
      break; 
     } 

    } 

    SDL_Quit(); 
    return 0; 

,這裏是我的輸入級:

#include <iostream> 
#include <SDL.h> 
#include "Input.h" 
using namespace std; 
string Input::check_event() { 
    while (SDL_PollEvent(&event)) { 
     if (event.type == SDL_QUIT) { 
      return "quit"; 
     } 
     else if(event.type == SDL_KEYDOWN){ 
      switch(event.key.keysym.sym){ 
      case SDLK_1: 
       return "1"; 
      } 
     } 
    } 
    return "null"; 
} 

任何幫助,將不勝感激

回答

3

SDL_PollEvent()文檔:

如果事件不是NULL,則下一個事件是,從隊列中刪除,並將 存儲在由事件指向的SDL_Event結構中。

分析代碼:

if (input.check_event() == "1") { 

刪除事件,不管它是什麼,從隊列中。

} else if (input.check_event() == "quit") { 

說第一個呼叫到check_event()是「跳槽」的返回值,則此調用將不會返回「跳槽」了,因爲這個信息現在丟失。

爲了解決這個問題,請致電check_event()每循環迭代一次,並把結果保存在一個臨時變量。然後在條件中僅使用該變量:

while (true) { 
    string event = input.check_event(); 
    if (event == "1") { 
     cout << "You pressed 1" << endl; 
    } else if (event == "quit") { 
     break; 
    } 
}