Godot Version
4.3
Question
I want to make something draggable. I’ve looked through other forums and it appears that Control nodes have a built in dragging ability, but I don’t know how to use it, or if it even does have one.
4.3
I want to make something draggable. I’ve looked through other forums and it appears that Control nodes have a built in dragging ability, but I don’t know how to use it, or if it even does have one.
Control nodes and drag and drop data built in, this is for functionality like dragging a image file and dropping it into a texture slot, I’m not sure if this is the “draggable” function that you are looking for.
Okay. What’s the best way to make something draggable then?
What do you mean by “draggable”
If I click on a Node, and hold the mouse down, then the Node will keep following the mouse until I let go.
For dragging/dropping something around the screen you want a CollisionObject2D and check the pickable
flag on it. Attach its mouse_entered()
signals to methods that set/unset some flag like hovering
and in the _process
method you check for that flag and if it’s set you check for Input.is_action_pressed("left_mouse_button")
you change the node’s global position to the mouse’s global position.
A pitfall to watch out for, and why the code below doesn’t set hovering = false
until the button is released, is when you move the mouse too fast.
extends Node2D
var hovering: bool = false
var dragging: bool = true
func _process(delta):
if hovering:
if Input.is_action_pressed("left_mouse_button"):
global_position = get_global_mouse_position()
dragging = true
elif Input.is_action_just_released("left_mouse_button"):
dragging = false
hovering = false
func _on_area_2d_mouse_entered():
hovering = true
If you have more than one node that can be dragged, possibly near or over each other, you want to track which node you track and don’t react in the mouse_entered
you already drag something.
Thank you!
This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.