How to play sound once on button hover?
Asked Answered
R

4

0

When I check is_hovered() on a button, and the mouse hovers over the button, the button plays the sound a bunch of times whenever the mouse moves while hovering. How do I fix this? Should I use some sort of boolean?

Rufena answered 5/10, 2023 at 17:35 Comment(0)
I
1

Rufena Should I use some sort of boolean?

Yes, you could either set your own flag to indicate that you are already playing a sound or there might be a flag already built into your audio player that indicates if it is playing a sound right now.

Icao answered 5/10, 2023 at 18:5 Comment(0)
C
1

Icao there might be a flag already built into your audio player that indicates if it is playing a sound right now.

There is. The issue for Sapient though depends on whether or not the sound is a loop.

If it's a looped sound, you could just check is playing before hitting play(), and do the reverse with stop().

If it's a "one-shot" sound, you can't rely on playing because it will be false once the sound finishes, in which case it would play again. If that's the case, you should handle it yourself with something like a bool.

Convivial answered 6/10, 2023 at 1:20 Comment(0)
H
1

Rufena
I assume you want the sound to play once when the mouse cursor starts to hover over the button, but not keep repeating it if the mouse cursor stays over it? In that case, yes, a boolean would be your way to go, since afaik Godot buttons do not have a specific mouse_entered event. So you define a boolean variable named "hovering" or something like that and set it to false. Then you track your mouse input and when you detect is_hovering and the variable is false, you set it to true and play your sound. If the variable is true and is_hovering is still true as well the next times your _input function is called, you leave it as is. Once you detect that is_hovering returns false, you set your own hovering variable to false also, so that the next time the mouse moves over the button, the sound will play again.
If you have many buttons with that desired behaviour, you could make your own class for this and define your own mouse_entered signal.

Heeley answered 6/10, 2023 at 8:23 Comment(0)
R
1

Buttons actually do have a mouse_entered signal inherited from Control which might be useful for this:

https://docs.godotengine.org/en/stable/classes/class_control.html#class-control-signal-mouse-entered

Ranice answered 6/10, 2023 at 19:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.