我想在Mainmenu中的鼠标内部按钮中放入鼠标时一次播放声音效果。问题在这里 - Mainmenu处于循环状态,所以我的声音一直都在重复。当某人将鼠标放在内部按钮中时,如何播放一次声音?
按钮:
if(mouse is in position X = <0,100> and Y = <0,100>){
drawButton( X = 0, Y = 0, X2 = 100, Y2 = 100);
}
按钮在循环中:
while( we are in MainMenu state )
{
if(mouse is in position X = <0,100> and Y = <0,100>){
drawButton( X = 0, Y = 0, X2 = 100, Y2 = 100);
}
}
声音:
Music Sound_1 = new Music("res/Sound/Sound_1.wav");
播放声音:
Sound_1.play(1.0f, 1.0f);
代码:
while( we are in MainMenu state )
{
if(mouse is in position X = <0,100> and Y = <0,100>){
Sound_1.play(1.0f, 1.0f); <- IT MUST PLAY JUST ONCE WHENEVER MOUSE IS IN BUTTON
drawButton( X = 0, Y = 0, X2 = 100, Y2 = 100);
}
}
您可以通过调用声音检查是否已经播放(使用示例声音变量_1):
if(mouse is in position) {
if(!sound_1.playing()) {
sound_1.play(1.0f, 1.0f);
}
drawButton(x,y,x2,y2);
}
使用Sound/Music对象具有光滑的.playing()方法,如果声音当前播放,它将返回boolean true,如果不是,则false。希望这会有所帮助:)
在调用循环之前,添加一个布尔值,该布尔值跟踪游戏是否应该播放声音:
boolean playSound = false;
然后,当您调用循环时,请执行此操作:
loop() {
playSound = true;
if (/**Mouse is on the button*/) {playSound = true;}
else {playSound = false}
//If playSound is true, then play the sound
if (playSound) {sound.play(1.0f, 1.0f);}
else
return;
}
应该起作用!
您需要设置一个布尔值来确定我们是否已经播放了声音。
boolean soundHasPlayed = false;
while( we are in MainMenu state )
{
if(mouse is in position X = <0,100> and Y = <0,100>){
if (!soundHasPlayed) // only do this if we haven't played the sound yet
{
Sound_1.play(1.0f, 1.0f);
drawButton( X = 0, Y = 0, X2 = 100, Y2 = 100);
soundHasPlayed = true; // don't play it again until we leave the button
}
}
else
{
// We left the button, so we can play it again if we ever enter the button again.
// (Omit this if you really only want it to play once, ever, even if they mouse over the button again.)
soundHasPlayed = false;
}
}