get_global_mouse_position() off centre?

Godot Version

4.5, 2D

Question

completely new to Godot and coding. currently trying to build a board-game-like scene. grid size is 16. i created two 16*16 pixel solid colours (think chess board game) and with the tilesetlayer node i painted my board. however, as the game progresses, i would like the selected tile (via mouse hovering) to look a little different as part of the ui so the person playing the game knows what tile they are selecting, so i added this different tile as a sprite2d node for now as a child of the tileset layer just so i can test the mechanic. this sprite tile is also 16 pixels. i used get_global_mouse_position(), thinking that it would snap to the tile my mouse hovers on, but somehow, it is off by 8 pixels both ways and i would really appreciate help so that it is fixed.

this is my current code:

extends Sprite2D

const GRID_SIZE = 16

#snaps tile_select to hovered board tile of the mouse

func _process(delta):
	
	position = get_global_mouse_position()
	var snapped_mouse_pos = position.snapped(Vector2(GRID_SIZE, GRID_SIZE))
	
	position = snapped_mouse_pos

this is what it looks like when i test it. notice where my mouse is and what the selected tile is.

the same thing happens on the y axis, meaning that my mouse may be found in the tile above the selected tile.

thanks in advance!

The simplest fix is to just subtract the offset you have measured.

This is not the issue but I’d change this part to the following code. Because this is a much cleaner and simpler way of doing it in my opinion.

var mouse_pos = get_global_mouse_position()
position = mouse_pos.snapped(Vector2(GRID_SIZE, GRID_SIZE))

About your issue, that’s a wild guess as there is not much information to go with but:

If your tilemaplayer position is not 0,0 (aka has a position offset) and if your sprite is child of it, then assigning the position of sprite will be on local coordinate, which is relative to the parent node (tilemaplayer), but not global position. You can check this easily if you change the code like this, and if you see it fixes it:

var mouse_pos = get_global_mouse_position()
global_position = mouse_pos.snapped(Vector2(GRID_SIZE, GRID_SIZE))

I just realized that Vector2.snapped() snaps to the nearest multiple, so that may also be an issue for you. You’d need more like a floor function, rather than nearest multiple.