Align an object with a grid

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lurgx

Hi guys I wanted to know how I could align an object to a grid or to the same godot grid, what I want to achieve is to make a drag and drop with automatic alignment but I don’t know anything about grid, the only and most basic thing that I managed to do was create the object at mouse position

:bust_in_silhouette: Reply From: bloqm

You can use something like this to get a position snapped to a grid:

var CELL_SIZE = 32 # or whatever

func position_snapped(pos:Vector2):
    return (pos / CELL_SIZE).floor() * CELL_SIZE

If you are using a TileMap you can use its map_to_world and world_to_map functions to transform world coordinates into grid positions.

:bust_in_silhouette: Reply From: Mison

If you have a Vector2 position for your object, you can use the built-in Vector2 function snapped(Vector2 by):

position = position.snapped(Vector2.ONE * grid_size)

replace grid_size with whatever grid size you are using.

From the docs:

yeah! thanks to all it served me

lurgx | 2021-06-15 18:15