I want to make the part snap to the nearest stud

I wanted to make a placement system, I already coded placing but I want to make each part/model have correct stud placement, basically i want to make it stick to the studs correctly by adding 0.5 to the x, y or z to the position, mostly happens when the part/model is too skinny, like by 1, 1, 1.

What I want is, the part/model will snap to any nearest stud.

This is not correct:


Model placed at the wrong

Another not correct result with a skinny part:


(Used cinematic camera feature for these two.)

Correct:


Snaps to a nearest stud.

Anyways, here’s the code:

local function updatePartPosition(part)
    local buildingType = localplayer.PlayerScripts.BuildingType.Value
	local buildinghintsfolder = game.Workspace.BuildingHintsFolder
	
	for i, v in buildinghintsfolder:GetChildren() do
		if v:IsA("BasePart") or v:IsA("Model") then
			if v.Name ~= localplayer.PlayerScripts.BuildingType.Value then
				v:Destroy()
			end
		end
	end

    local mouseposition = mouse.Hit.p
    mouse.TargetFilter = part
    part.Anchored = true
    part.CanCollide = false
    part.Transparency = 0.5
    part.Position = Vector3.new(math.floor(mouseposition.X), math.floor(mouseposition.Y)+0.5, math.floor(mouseposition.Z))
end

I assume that the size on each axis is an integer. Try this.

part.Position = mousePosition // 1 + .5 * Vector3.new(part.Size.X % 2, part.Size.Y, part.Size.Z % 2)

Edit: I originally forgot to include the floor division. I’ve added it now.

1 Like

You can do something like this too;

local function toStudSpace(origin, studSize)
      return math.floor((origin + studSize / 2) / studSize) * studSize
end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.