How to make my area2d position snap to tile size and follow mouse position at same time?

Godot Version

4.2

Question

how to make my area2d position snap to tile size and follow mouse position at same time?
i want my area2d follow my mouse and my cursor more or less in middle of my area2d.
it working if my area2d size like 32, 96 , but if size lie 64,128 it wont snap anymore.

my tile size 32x32
this my code

func cursor_pos() -> void :
	var new_pos : Vector2 = tile_map.map_to_local( tile_map.local_to_map( get_global_mouse_position() )) 
	cursorAreaBase.global_position = new_pos

basically you divide mouse by grid size, floorf the result, multiply by grid size. then offset mouse position by HALF grid size so it is centered

extends Sprite2D

var m_grid_size : Vector2

func _ready():
	m_grid_size = get_rect().size # grid size is size of sprite
	
func _process(delta):
	
	# divide mouse position by grid size, use floorf to disard decimal
	# then multiply by grid size
	var v_x : float = floorf(get_global_mouse_position().x / m_grid_size.x) * m_grid_size.x
	var v_y : float = floorf(get_global_mouse_position().y / m_grid_size.y) * m_grid_size.y
	
	#set global position
	global_position = Vector2(v_x, v_y);
	
	# offset by HALF grid size
	global_position = global_position + (m_grid_size / 2)

1 Like

thank you, its work.

1 Like

I’m trying to make a game board ala chess / checkers. I have my board pieces that I’m trying to place in a grid. Can I use this same get_rect().size to get the size of the cell to programmatically build the gameboard to variable height x width.