Search code examples
godotgdscriptgodot4

Button doesn't want to understand that it is hovered with mouse after method show()


My buttons are displayed (show method) after a short pause, and if I hover the mouse cursor over the position where the button will be and leave it, the button will not realize that it is hovered. This is fixed when moving the mouse, but I really want to fix this little problem.

I used base signals mouse_entered() and mouse_exited()

After show() buttons must understand is mouse in or not. That's all(


Solution

  • When you make the Control visible, you could check if the mouse pointer is inside its rectangle.

    For that let us begin by getting the mouse position in local coordinates:

    var local_mouse_pos := get_local_mouse_position()
    

    Since that is in local coordinates, negative coordinates are outside of the Control. So we only need to check if they are between zero and the Control's size. In this case I defined a rectangle and checked if it has the mouse position:

    var local_mouse_pos := get_local_mouse_position()
    var hovering := Rect2(Vector2(), size).has_point(local_mouse_pos)
    

    Be aware that this won't detect if there is another Control on top.

    Assuming you have your logic on the mouse_entered signal, you can always emit it yourself:

    var local_mouse_pos := get_local_mouse_position()
    var hovering := Rect2(Vector2(), size).has_point(local_mouse_pos)
    if hovering:
        mouse_entered.emit()