【发布时间】: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,这就是音效最终每帧都播放的原因,但我不确定为什么以及在哪里/何时这正在发生,或者如何解决它。
【问题讨论】: