Rotation relative placing not working correctly on building system with grid

I’m making a building game with a grid (default 1 stud grid), and it works fine in 90 degree angles, except for placing blocks on the side of other, rotated blocks, where the block is offset is weirdly.

The wood (center) block is the block being placed off of, and the stone blocks are the ones that were placed on the side of it.

An ever weirder issue happens when you try to place it on the side of the rotated block, where it partially clips inside the block.

image

This issue isn’t present when the grid is disabled, so I think it’s an issue with the way the grid works.

image

How would I make the grid relative to the part? Here’s the code:

Related Code
local function round(numberToBeRounded:number,rounding:number)
	local r = 0
	
	if rounding > 0 then
		r = math.round(numberToBeRounded/rounding)*rounding
	else
		r = numberToBeRounded
	end
	
	return r
end

local function snapToGrid(pos:Vector3)
	return Vector3.new(
		round(pos.X,grid),
		round(pos.Y,grid),
		round(pos.Z,grid)
	)
end

local function update()
	if selectedBlock and mouse.Target then
		if preview == nil then
			createPreview()
		end

		local hit = mouse.Hit
		local target = mouse.Target
		local tars = mouse.TargetSurface

		mouse.TargetFilter = preview 

		local pos1 = mouse.Hit.Position

		pos = snapToGrid(pos1)

		local off = Vector3.new(0,0,0)

		if tars == Enum.NormalId.Top then
			off = target.CFrame.UpVector
		elseif tars == Enum.NormalId.Right then
			off = target.CFrame.RightVector
		elseif tars == Enum.NormalId.Front then
			off = target.CFrame.LookVector
		elseif tars == Enum.NormalId.Bottom then
			off = -target.CFrame.UpVector
		elseif tars == Enum.NormalId.Left then
			off = -target.CFrame.RightVector
		elseif tars == Enum.NormalId.Back then
			off = -target.CFrame.LookVector
		end

		pos += (off*(mainPart.Size/2))

		preview:PivotTo(CFrame.new(pos)*curRot)
		preview.Parent = workspace.Previews
	end
end

Can anyone help with this? I’ve tried figuring this out but I couldn’t find any solutions.

Try using floor for your grid placement. I don’t see anything other than that so try that.

By floor, do you mean the function math.floor? Because I already use a similar function (math.round)

I’ve tried using math.floor (if that’s even what you were talking about), and it didn’t change anything.