Sprite2D follow mouse and snap to Tile Grid

Godot Version

V4.2.2.stable.official

Question

Hi. I have a Sprited2D that needs to follow the mouse cursor, additionally I need it to snap to the Tile grid that I have. I started by converting my mouse coordinates local_to_map and then setting the position of the sprite to that value but it does not work correctly.

The Sprite does move but as the cursor moves further away it gets out of sync.

I am new to programming, I apologize if the question is not put properly.

tile_map.local_to_map() method returns a Vector2i object which is displayed as “(1,1), (1,2)” on the tilemap.
What you might need to do is to translate them to realworld coordinates.
I would do (assuming your scale is set to 1):

position = tilepos * tile_map.tile_size