Line2D/3D procedural grid snapping

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

I’m attempting to make libraries for strategy games/puzzle games, most of which require a click and drag path for players to use. However, every attempt I’ve made of making each point bound to a grid has failed. Hopefully I’m overthinking this, because I was unable to find any documentation on procedural grid snapping online.
Most attempts I’ve made usually revealed one bug that lead to another. I can upload example code if needed.

:bust_in_silhouette: Reply From: Zylann

Grid snapping boils down to using the Vector2.snapped() function, or floor(x / step) * step on each coordinate, where step is how big a cell of your grid is. Then if you want the result to be centered, add a half-cell to it.

For example, to snap coordinates you would get with var pos = get_local_mouse_position(), you would do pos = pos.snapped(Vector2(32,32)) if your cell size is 32x32 pixels, add pos += Vector2(16,16) to center it, and apply the resulting position to the point of your line.

See Vector2 — Godot Engine (stable) documentation in English

Alternatively if you use TileMap you can also use world_to_map() to get tile coordinates TileMap — Godot Engine (stable) documentation in English

Oh yes, basic snapping is well and fine. Flooring, centering, and moving back is easy. The hardest part of this is trying to make it not have diagonals, in a sort of zig zag pattern. I’d imagine one would have to continuously split between two points until no diagonals remain, but how I’ve done it has yet to work flawlessly.

Nathan R. | 2022-01-28 22:42