Count bool true / false change inside the game update loop
What would be the best way to calculate how many times the bool flag has been changed from false to true inside a game refresh loop? For example, if I have this simple example below where if you hold down the "A" button, the Input class sets the bool class of the Game class to true, and if you release it, it sets to false and the counter inside the Game class, which takes into account how many times the permission has been changed from true to false. For example, if you press "A" and release twice, the counter should update to 2. After updating Game :: Update () at 60 frames per second, the counter will be erroneous in the current approach. To fix this, I moved the check and counter inside the SetEnable instead of the update loop.
// 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;
*/
}
source to share
If I get you right, you want to count how many times enable_ changes. Your code has a small flaw, imagine this example:
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
A function that can fix this might look like this:
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;
}
}
source to share