【问题标题】:(C++) Executing an instruction inside a game loop once (SFML)(C++) 在游戏循环中执行一次指令 (SFML)
【发布时间】:2020-08-07 02:14:26
【问题描述】:

这个问题的答案在写到一半时就出现了稍后。

我正在使用 SFML,我有许多按钮,当鼠标光标悬停在其中一个上时,我想播放一个 blip 音效...

这是按钮类中的方法,用于测试鼠标光标和按钮之间的碰撞:

bool menu_button::button_collision() {

    if ((cursor.getPosition().x <= (text_box.getPosition().x)+text_box.getSize().x/2)
        && (cursor.getPosition().x >= (text_box.getPosition().x) - text_box.getSize().x / 2)
        &&(cursor.getPosition().y <= (text_box.getPosition().y) + text_box.getSize().y / 2)
        && (cursor.getPosition().y >= (text_box.getPosition().y) - text_box.getSize().y / 2)) {
        
        text.setFillColor(sf::Color(sf::Color::Yellow));
        coll = true;
    }
    else { text.setFillColor(sf::Color(sf::Color::White)); coll = false;  }
    return coll;
}

这是当光标悬停在按钮上时播放音效的代码:

for (int j = init; j < limit; j++) { //This is a loop that tests every button.
        collision = buttons[j].button_collision();// 'collision' is a boolean that stores the value returned by the collision function.

        if (collision == true) {

                m_hover.play();

            }
//Other instructions go here...
}

现在这段代码工作得很好,但由于它在游戏循环中,每帧都重复,所以声音将每秒播放“x”次(“x”是每秒的帧数)这不是我想要的,所以我将代码修改为如下所示:

for (int j = init; j < limit; j++) {
        collision = buttons[j].button_collision();

        if (collision == true) {

            if (collision2 == false) { // 'collision2' is another boolean, that becomes true AFTER the sound-effect have already played.

                m_hover.play();
                collision2 = true;

            }

        }
//Other instructions go here...
}

现在,声音效果会在光标第一次悬停在按钮上时播放,但只是第一次,然后它会完全静音,所以显然我们还有另一个问题...

所以我在父条件下添加了这一行(测试collision的那一行):

else { collision2 = false; }

我认为这会起作用,但现在我回到了第一个问题,在光标悬停在按钮上的每一帧中,音效都会不断播放......

经过一番修改,我意识到collision 每帧都会重置为false,这就是音效最终每帧都播放的原因,但我不确定为什么以及在哪里/何时这正在发生,或者如何解决它。

【问题讨论】:

标签: c++ sfml


【解决方案1】:

事实证明,collision 每帧重置为false 的原因是因为我忘记了整套指令包含在测试每个按钮的for 循环中,所以碰撞测试发生在每帧的每个按钮,并且每次返回的值都存储在collision 中,这意味着collision 将其值重置为每帧“y”次(“y”是屏幕上的按钮数在那一刻),并且由于没有光标悬停在它们上面的所有其他按钮的碰撞值将是false,因此将碰撞值每帧重置为 false 是非常有意义的。

现在这个问题的解决方案很清楚了,我所要做的就是用一个布尔值数组替换 collision2 布尔值,这个数组的每个元素对应于其中一个按钮的碰撞值,这意味着这个数组的大小将等于我正在使用的按钮总数...

所以现在代码应该是这样的:

for (int j = init; j < limit; j++) {
        collision = buttons[j].button_collision();

        if (collision == true) {

            if (collision2[j] == false) {// 'collision2' is an array that stores the collision values for each button.

                m_hover.play();
                collision2[j] = true;
            }

        }
        
        else { collision2[j] = false; }

//Other instructions go here...
}

现在它可以工作了!对这整件事感到沮丧,我感到如释重负......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    相关资源
    最近更新 更多