Godot Version
4.3
Hello,
I have a script that manages to drag and drop data from one node to another (the texture, from a TextureRect
node to another one), but whenever I “drop” the data outside of the bounds of one of the valid nodes it completely disappears. I’d like for it to snap back to it’s last known position somehow.
I know I should be using _notification(what:int)
and in some of my tests I’ve managed to make the data snap back to it’s absolute original position, but not it’s last known one.
I was hoping someone with more knowledge could look at my code and tell me what to do and how it works?
My Code:
extends TextureRect
# Copy, check if can paste, then paste = illusion of drag and drop
# __________________________________________________________________________________
# For snapping data back to original place
var lastKnownTexture : Texture2D = self.texture # PROBLEM - Not really last known...
# Triggers when you click and drag
func _get_drag_data(at_position: Vector2): # Should return data
# __________________________________________
# Create preview of what we're dragging
var preview_texture = TextureRect.new()
# Define it's properties so we can see it:
preview_texture.texture = self.texture #make it's texture THIS node's texture
# add the preview to the scene tree (doesn't make visible yet)
var preview = Control.new()
preview.add_child(preview_texture)
# Set mouse offset
preview_texture.position -= get_rect().size/2 # Size is a Vector2
# make preview visible as drag preview
set_drag_preview(preview) # set_drag_preview must accept a control node
# __________________________________________
# delete texture from original data holder (illusion that we picked it up)
self.texture = null
#return what we want to "drag" (basically copy)
return preview_texture.texture
# since we're deleting the og texture we'll return the copy we made in the preview func
# Triggers when you hover over another node with dragged item
func _can_drop_data(at_position: Vector2, data: Variant): # should return a bool, data is what we're dragging.
# Checks whether the data we're dragging can be applied to what we're hovering over
# (basically checks if can succesfully paste)
return data is Texture2D # Will return true/false
# Triggers when you drop held item
func _drop_data(at_position: Vector2, data: Variant) -> void: # data is what we're dragging.
# Assign that dragged data over what we're hovering over
self.texture = data
# use the _notification func to tell code if drag was succesful
func _notification(what:int):
if what == NOTIFICATION_DRAG_END && is_drag_successful() == false:
# make self.texture our last known texture (was original one)
self.texture = lastKnownTexture # PROBLEM - Not really last known...
Thank you for reading!