Snapping to the middle of a Grid

Hey

I made a grid placement system and I’ve been scratching my head all day trying to figure out how to snap objects to the middle of a grid, the grid that I am using is a 5x5 grid.

This is my code to snap objects to grid:

local function Round(x, mult)
	return math.floor((x / mult) + 0.5) * mult
end	

x = Round(x,1.25)
z = Round(z,1.25)

This is what happens currently

I would like to instead only snap to the middle of the grid

2 Likes

Try rounding to the nearest 5 studs instead of the nearest 1.25 studs.

If it gets stuck on the corners, try offsetting it by 5/2 = 2.5, like so:
local gridSize = 5
x = Round(x - gridSize/2, gridSize) + gridSize/2
z = Round(z - gridSize/2, gridSize) + gridSize/2

Subtracting half the grid size has the effect of moving it by half a grid cell, but because it’s before rounding it still just gets rounded to the corners. Later adding the half grid cell back

a) makes it centered on a grid cell
b) fixes the offset we subtracted earlier (otherwise the building would not match where the mouse is)

1 Like

For some reason the following code produced this result

local gridSize = 5
x = Round(x - gridSize/2, gridSize) + gridSize/2
z = Round(z - gridSize/2, gridSize) + gridSize/2

So I tried

local gridSize = (5)/2
x = Round(x - gridSize/2, gridSize) + gridSize/2
z = Round(z - gridSize/2, gridSize) + gridSize/2

and it was fixed

1 Like

Cool! Glad I could help :slight_smile: :+1: