How to center-align the TextureRect used with set_drag_preview()?

Godot Version

4.2.2

Question

Hi, I use the following code to display a dragged item preview:

    func _get_drag_data(at_position: Vector2) -> Variant:
		var drag_preview := TextureRect.new()
		drag_preview.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
		drag_preview.texture = icon_texture_rect.texture
		drag_preview.custom_minimum_size = Vector2(80, 80)
		drag_preview.modulate = Color(1, 1, 1, 0.75)
		set_drag_preview(drag_preview)
		# return this item slot as the thing to be dragged
		return self

It works, but the dragged rectangle is being dragged by its top-left corner, while I’d like the mouse pointer to drag its middle:

screenshot

Does anybody please have a suggestion on how to implement this? I have not found a suitable method in TextureRect and Control docs

Thanks

This doesn’t work because whatever position you set for the drag_preview is overwritten by the engine’s implementation of set_drag_preview. You can make it work using two nodes, though:

func _get_drag_data(at_position: Vector2) -> Variant:
	var drag_preview := Control.new()

	var texture_rect := TextureRect.new()
	texture_rect.expand_mode = TextureRect.EXPAND_IGNORE_SIZE
	texture_rect.texture = icon_texture_rect.texture
	texture_rect.custom_minimum_size = Vector2(80, 80)
	texture_rect.position = -0.5 * texture_rect.custom_minimum_size
	texture_rect.modulate = Color(1, 1, 1, 0.75)

	drag_preview.add_child(texture_rect)

	set_drag_preview(drag_preview)

	return self
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.