How can we avoid the problem that the position of the dragged object lags behind the mouse position when dragging quickly?

Godot Version

Godot 4.3

Question

I implemented the drag function with the following code (this is the code provided in the official documentation). However, I found that when dragging quickly, the position of the dragged object will lag behind the position of the mouse. Are there any optimization methods to make the dragged object closely follow the mouse?

extends Node


var dragging = false
var click_radius = 32 # Size of the sprite.


func _input(event):
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT:
		if (event.position - $Sprite2D.position).length() < click_radius:
			# Start dragging if the click is on the sprite.
			if not dragging and event.pressed:
				dragging = true
		# Stop dragging if the button is released.
		if dragging and not event.pressed:
			dragging = false

if event is InputEventMouseMotion and dragging:
		# While dragging, move the sprite with the mouse.
		$Sprite2D.position = event.position

See Customizing the mouse cursor — Godot Engine (stable) documentation in English

Outside of having a good enough frame rate to mitigate the delay or hiding the OS mouse cursor you cant improve much here as a “software” mouse cursor will always lag behind 1-2 frames behind your “hardware” mouse cursor.

2 Likes

I don’t know of a proper fix (and I haven’t looked). If you can’t find one, you could experiment with extrapolation as a workaround. I imagine it might look a bit janky if the cursor is being moved with a lot of jerk though.