• Godot Help
  • Best way to detect control being dropped in a wrong place

_can_drop_data / _drop_data works great when you drop the object in a accepted place, but how can I detect when the user drops in a spot that doesn't accept that drop?

When the user drops an object in a spot that doesn't accept the drop, the _drop_data function is not called. Instead, the _drag_exit function is called on the control that the user dragged the object out of. You can handle unwanted drops in this function.

Here's an example of how you could use the _drag_exit function to handle unwanted drops:

func _drag_exit(control, position):
    if control == $accepted_drop_zone:
        # The user dragged the object out of the accepted drop zone without dropping it,
        # so cancel the drop operation and move the object back to its original position.
        original_position = get_global_transform().origin
        set_global_position(original_position)

In this example, the _drag_exit function is called when the user drags the object out of the $accepted_drop_zone control. If this happens, the function sets the object's position back to its original position before the drag operation started, effectively canceling the drop operation.

You could modify this example to suit your needs. For instance, you could display a message to the user indicating that the drop was invalid or play a sound effect to give feedback.

    ManHua I am not finding any function called _drag_exit in Godot 4.0 and its not working as in its not firing that event

    5 months later

    I've got the answer. It was buried in the docs.

    Use the NOTIFICATION_DRAG_END notification:

    func _notification(notification_type):
        match notification_type:
    	    NOTIFICATION_DRAG_END:
    		    print("END")

    You can use the is_drag_successful Control class method to figure out if it was ended successfully.

    Or the gui_is_drag_successful method on Viewport.