【问题标题】:Count bool true/false change inside game update loop在游戏更新循环中计算布尔真/假变化
【发布时间】:2017-04-10 20:46:20
【问题描述】:

在游戏更新循环中计算 bool 标志从 false 变为 true 的次数的最佳方法是什么?例如,如果我在下面有这个简单的示例,如果您按住按钮“A”按下 Input 类将 Game 类的 enable bool 设置为 true,如果您释放它,则将其设置为 false,并且 Game 类中的计数器计数启用多少次从真更改为假。例如,如果您按“A”并释放两次计数器应更新为 2。让 Game::Update() 以 60fps 更新,当前方法的计数器将是错误的。为了解决这个问题,我将检查和计数器移到了 SetEnable 中,而不是 Update 循环中。

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

【问题讨论】:

  • 在您更改状态时更新计数器。因此,如果按下 KEY_A,并且 enable_ 为 false,则更改为 true 并计数。
  • 计数器并没有真正计算启用更改的次数。
  • 由于问题不清楚,我不得不重新措辞并添加更多细节。让我知道是否需要进一步更新。

标签: c++


【解决方案1】:
void Game::Update()
{
    if (key == KEY_A && ! enable_)
    {
        enable_ = true;
        ++counter_;
    }
    else if (key == KEY_B)
        enable_ = false;
}

【讨论】:

  • 您能否根据我的新编辑更新您的答案?
【解决方案2】:

如果我猜对了,您想计算 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;
    }
}

【讨论】:

    猜你喜欢
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    相关资源
    最近更新 更多