inc0gnizant
inc0gnizant

Reputation: 21

Detect Mouse Movement and Direction in Godot

I am making the settings menu for a game in Godot 3.5 which has a progress bar node for the volume.
I want players to drag their mouse to adjust the volume, like so:
image of volume bar

The problem is that I don't know how to detect where and how much the mouse is moving to change the value of the progress bar accordingly. I was wondering if there was a way to detect and measure mouse movement when it enters a node.

I tried to use get_global_mouse_position(), stored it in a variable, used a timer for a delay and then again checked it, then subtracting both, I thought I would get the mouse movement but it didn't work and the progress bar remained the same. Although, even if it had worked, it would not have been smooth or changing realtime...

I hope you'd like to help, THANKS!

Upvotes: 2

Views: 1119

Answers (1)

Theraot
Theraot

Reputation: 40295

I recommend using HSlider for volume settings.


Since you want to use a ProgressBar...

A way to do this would be with _gui_input in an script attached to the ProgressBar:

func _gui_input(event:InputEvent) -> void:
    var mouse_event := event as InputEventMouse
    if mouse_event != null:
        if mouse_event.button_index == BUTTON_LEFT and mouse_event.pressed:
            prints(mouse_event.position)

Here the position you get would be in local space of the ProgressBar.


We could compute the value from the x (position.x) and the width (rect_size.x):

   x         value - min_value
------- = -----------------------
 width     max_value - min_value

=>

                            x
 (max_value - min_value) ------- = value - min_value
                          width


=>

value = min_value + (max_value - min_value) * x / width

Note: Be aware that the above computation does not take borders into account.


Addendum: I notice you explicitly ask "how much the mouse is moving". Well, if the event is an InputEventMouseMotion, it has a relative property that will tell you how much it moved since last event.

Upvotes: 1

Related Questions