How does roblox studio built in snap to grid work?

Hello!
I am making a building system but I am not so good at math.

I expect it to do what roblox studio built in snap to grid does. Here’s a video.

My snap to grid script works right only sometimes, for example (1,1,1), (3,3,3), (5,5,5), (1,3,1) parts will snap but (2,2,2), (4,4,4), (1,2,1) parts won’t snap right. (1,3,1) part can be split in 3 (1,1,1) parts and there is a middle part, but (1,2,1) part will have only 2 (1, 1, 1) parts and there is no part to say that is in the middle, so it will be snapped some weird way and that’s the issue.

my current code looks like this
the important part is inside the OnMouseMove function

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local Players = game:GetService("Players")

local Placeables = ReplicatedStorage:WaitForChild("Placeables")
local Events = ReplicatedStorage:WaitForChild("Events")
local PlaceObjectEvent = Events:WaitForChild("PlaceObject")

local LocalPlayer = Players.LocalPlayer
local camera = workspace.CurrentCamera
local mouse = LocalPlayer:GetMouse()

local object = Placeables:WaitForChild('3x3x3'):Clone()
object.Parent = workspace

function snap(vector)
	return Vector3.new(math.round(vector.X),math.round(vector.Y),math.round(vector.Z))
end

local raycastParams = RaycastParams.new()
raycastParams.FilterType = Enum.RaycastFilterType.Exclude
function GetRaycast(object)
	raycastParams.FilterDescendantsInstances = {LocalPlayer.Character, object}
	local mousePosition = UserInputService:GetMouseLocation()
	local unitRay = camera:ViewportPointToRay(mousePosition.X, mousePosition.Y)
	local raycastResult = workspace:Raycast(unitRay.Origin, unitRay.Direction * 500, raycastParams)	
	return raycastResult
end


function OnMouseMove()
	local raycastResult = GetRaycast(object)
	if raycastResult then
		local objectSize = object:GetExtentsSize()
		
		local snapedCFrame = CFrame.new(snap(raycastResult.Position + (raycastResult.Normal * objectSize) / 2))
		object:PivotTo(snapedCFrame)
	end
end

mouse.Move:Connect(OnMouseMove)

It’s also important to say that I want to add rotating later on.
Can someone tell me if there is any simple way to achieve what I showed on the video or how I can edit my current script to find an offset for even parts?

1 Like

Can’t you take the CFrame + Vector3.one or maybe + Vector3.new(0.5, 0.5, 0.5)

I would imagine something like that would fix it
Also I’m talking about the already snapped CFrame, so like object:PivotTo(snapedCFrame + Vector3.one)

1 Like

So I did this and now (2,2,2) part is alligned in the grid but it’s flying one stud above where it’s supposed to be
image
it seems that (4,4,4) part works right thought

Just try to experiment with the values to get it right