2017-04-10 31 views
3

在遊戲更新循環中,將bool標誌從false更改爲true的最佳方式是什麼?例如,如果我在下面有這個簡單的例子,如果按住按鈕「A」,Input類將Game類的啓用布爾值設置爲true,如果你釋放它,則將其設置爲false,並將Game類中的計數器設置爲false啓用次數從真變爲假。例如,如果按「A」並釋放兩次計數器應該更新爲2.在60fps更新Game :: Update()時,計數器將與當前方法錯誤。爲了解決這個問題,我將SetEnable中的檢查和計數器移到了Update循環中。在遊戲更新循環中計數bool真/假更改

// Input class 

// Waits for input 
void Input::HandleKeyDown() 
{ 
    // Checks if key A is pressed down 
    if (key == KEY_A) 
     game.SetEnable(true); 

} 

void Input::HandleKeyUp() 
{ 
    // Checks if key A is released 
    if (key == KEY_A) 
     game.SetEnable(false); 

} 

// Game class 

void Game::SetEnable(bool enable) 
{ 
    if(enable == enable_) 
     return; 

    enable_ = enable; 

    //Will increment the counter as many times A was pressed 
    if(enable) 
     counter_ += 1; 
} 

void Game::Update() 
{ 
    // Updates with 60fps 
    // Will increment the counter as long as A is pressed 
    /* 
    if(enable_ == true) 
     counter_ += 1; 
    */ 
} 
+1

更新在您更改狀態的情況下櫃檯。所以如果按下KEY_A,並且enable_爲false,則更改爲true並計數。 –

+1

計數器並不真正記錄啓用更改的次數。 –

+1

由於問題不明確,我不得不改寫和添加更多細節。讓我知道是否需要進一步更新。 – sabotage3d

回答

3
void Game::Update() 
{ 
    if (key == KEY_A && ! enable_) 
    { 
     enable_ = true; 
     ++counter_; 
    } 
    else if (key == KEY_B) 
     enable_ = false; 
} 
+0

您能否根據我的新編輯更新您的答案? – sabotage3d

1

如果我得到你的權利,你要計算時間enable_多少變化。你的代碼有一個小瑕疵,想象一下這個例子:

enable_ = false 
counter = 0 
update gets called, key is A -> enable_ = true, counter = 1 
update gets called, key is B -> enable_ = false, counter remains 1 

功能可能會解決這個問題可以看一下,例如,像這樣:

void Game::Update() { 
    if (key == KEY_A && !enable_) { // key is A and previous state is false 
     ++counter; 
     enable_ = true; 
    } 
    if (key == KEY_B && enable_) { // key is B and previous state is true 
     ++counter; 
     enable_ = false; 
    } 
}