1
\$\begingroup\$

I'm trying to make a button that plays a sound when hovering above it with the cursor

So far I created a class which extends the scene2d TextButton and I'm adding a FocusListener. The problem is that the sound is played a lot of times when hovering because this event fires not only once but as long as the button is focused.

//When button is hovered
this.addListener(new FocusListener() {

        public boolean handle(Event e) {

            SoundManager.play(hoverSound);

            return true;
        }
});

I also tried to make a variable soundPlayed which toggles if the sound is played once but this leads to the sound playing only one time because I don't know how to detect if the button is not focused anymore so i can reset the variable.

Thanks for the help.

\$\endgroup\$
  • \$\begingroup\$ You could try using the sound as a music object instead of a sound object as sounds are more for fire and forget effects. Just play the music continuously and turn volume up on hover. \$\endgroup\$ – dfour May 10 '18 at 11:59
  • \$\begingroup\$ but if i understand that correctly i still need to detect when the button is not focused any more and thats the thing what leads to the problem. i know there is a method for the button class called isOver which is true if the button is focused but it seems like a very bad solution for the problem because then i need to check that every time in the gameloop. \$\endgroup\$ – BlakkM9 May 11 '18 at 20:46
1
\$\begingroup\$

I'm assuming you want to play the sound only once during the whole time of the hover.

Since SoundManager does not track sounds it plays, you want to set a flag preventing from playing the sound twice. Then, you should use enter and exit functions provided by ClickListener to reset the flag when you go outside of the actor (your button).

public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor)
{
    if (!soundPlayed)
    { 
        SoundManager.play(hoverSound)
        soundPlayed = true;
    }
}

public void exit(InputEvent event, float x, float y, int pointer, Actor toActor)
{
    soundPlayed = false;
}

This way, sound will be played only once during hover, and can be replayed if mouse isn't hover anymore

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.