Snap to grid building system not working on some axises

Im trying to make a basic snap to grid system for placing blocks however the blocks sometimes phase through eachother on certain axises
My code currently looks like this

local UIS = game:GetService("UserInputService")

local player = game.Players.LocalPlayer
local block = game.ReplicatedStorage.Block:Clone()
block.Parent = workspace
local mouse = player:GetMouse()
mouse.TargetFilter = block
local grid = 4

local function snap()
	local pos = mouse.Hit
	local target = mouse.Target
	local X = math.floor(pos.X/grid+0.5)*grid
	local Y = math.floor(pos.Y/grid + 0.5) * grid
	local Z = math.floor(pos.Z/grid+0.5)*grid
	return Vector3.new(X,Y,Z)
end

mouse.Move:Connect(function()
	local newpos = snap()
	print(newpos)
	block.Position = newpos
end)

UIS.InputBegan:Connect(function(input,gameProcessed)
	if not gameProcessed then
		if input.UserInputType == Enum.UserInputType.MouseButton1  then
			local newblock = block:Clone()
			newblock.Parent = workspace
			newblock.CanCollide = true
		end
	end
end)

image
image
image
image
This is what the snap to grid turns out to do and from what i see when it is used on the negative axis it phases through blocks
Does anyone know a fix?

1 Like

It also doesnt work when placing underneath blocks
image

1 Like

your system doest round corectly in the negative axis

1 Like

this should work instead of math.floor

local round = function(num)
	local output
	if num >= 0 then
		output = math.floor(num+0.5)
	else
		output = math.floor(math.abs(num)+0.5)*-1
	end
	return output
end

justwrite:

local Variable X/Y/Z = round(pos.Y/grid ) * grid

image
I put it in and it still doesnt work

1 Like

because the numbers in the negatives might we need to reverse it to math.ceil and num - 0.5? (nvm cant be because its uses math.abs)

1 Like

boostinnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn

1 Like

I use it like this :

	gridposition = Vector3.new(round(round(hit.X)/tilesize)*tilesize,0,round(round(hit.Z)/tilesize)*tilesize)
1 Like

just use it like this:

round(round(pos.X)/grid)*grid

if you want that i explain why it has to be rounded twice then just say it