Cant drag transparent window properly

Godot Version

4.3

Question

How do i fix this code? im making a tamagotchi game and i need to drag the window when you click on the body of ther tamagotchi. When its dragged, it jitters and somtimes teleports too far. thanks!

var dragPoint = null
func _on_area_2d_input_event(viewport: Node, ev: InputEvent, shape_idx: int) -> void:
	if ev is InputEventMouseButton:
		if ev.button_index == MOUSE_BUTTON_LEFT:
			if ev.pressed:
				# Grab it.
				dragPoint = Vector2i(get_global_mouse_position()) - get_tree().get_root().position
			else:
				# Release it.
				dragPoint = null
	
	if ev is InputEventMouseMotion and dragPoint != null:
		get_tree().get_root().set_position(Vector2i(get_global_mouse_position()) - dragPoint)


image

is there a better way to get the mouse drag amount?

get_tree().root will give you the window, which I believe uses screen-space coordinates, but get_global_mouse_position() uses the canvas layer/window coordinates.

To get the mouse screen coordinate position use DisplayServer.mouse_get_position()

1 Like

Thank you so much!

This is the full code if anyone needed it:

var dragPoint = null

# Called when the node enters the scene tree for the first time.
func _ready():
	get_tree().get_root().set_transparent_background(true)
	var poly : PackedVector2Array = $Poly.polygon
	DisplayServer.window_set_mouse_passthrough(poly)

func _input(event: InputEvent) -> void:
	if event is InputEventMouseMotion:
		if not dragPoint: return
		get_tree().root.position = DisplayServer.mouse_get_position() - Vector2i(dragPoint)
	
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed == false:
				dragPoint = false

func _on_area_2d_input_event(viewport: Node, ev: InputEvent, shape_idx: int) -> void:
	if ev is InputEventMouseButton:
		if ev.button_index == MOUSE_BUTTON_LEFT:
			if ev.pressed:
				# Grab it.
				dragPoint = get_local_mouse_position()

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