2dmousegodot

How do I create a click and drag system for a sprite in Godot?


I'm working on a game in Godot and I'm trying to create a system where I can click and hold onto a sprite and drag to move that same sprite but I'm having a bit of trouble figuring it out.

I've tried solutions such as looking for a mouse node, looking for mouse signals etc but couldn't find anything for either of them. I've also tried checking for coordinates of the mouse and moving it there but couldn't find a way to do this either. I've been trying to figure this out for a while so I'd appreciate the help.


Solution

  • Godot built-in drag and drop support only exist for Controls not for Node2D (such as Sprite2D). So, first consider if you actually need a Sprite2D or would TextureRect be better. The Sprite2D is a graphic object in the 2D game world, and the TextureRect is a graphic object in the UI.


    Now, if you really want to drag an Sprite2D... We can break the problem twofold: