Skip to content

Instantly share code, notes, and snippets.

@rafaskb
Last active January 26, 2020 14:22
Show Gist options
  • Save rafaskb/f65ced43496c457a385fe024528d054a to your computer and use it in GitHub Desktop.
Save rafaskb/f65ced43496c457a385fe024528d054a to your computer and use it in GitHub Desktop.
Static method that adds click and hover sounds to a Scene2D button.
/** Adds a {@link ClickListener} to the given button that plays sounds. */
public static void addSoundToButton(Actor button, Sound sound) {
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
// Play click sound.
sound.play();
}
@Override
public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
// Ignore if mouse was already over
if(isOver()) return;
super.enter(event, x, y, pointer, fromActor);
// Ignore if mouse is not over
if(!isOver()) return;
// Ignore if fromActor is a child
Actor actor = event.getListenerActor();
Actor from = fromActor;
while(from != null) {
if(from == actor) return;
from = from.getParent();
}
// Play hover sound
sound.play();
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment