Snapping player dragged objects to stud grid

I have a building system in my game which lets players place down conveyor belts and things but they are off the grid, which means that players cant cleanly connect parts to other parts. How can I make it so it snaps to grid?

This is my code for getting the position that the item should be at:

				runs.RenderStepped:Connect(function()
					if PlacingObject then
						mouse.TargetFilter = preview
						local objectCFrame = CFrame.new(mouse.Hit.Position.X, mouse.Hit.Position.Y + preview.MainPart.Size.Y / 2, mouse.Hit.Position.Z)
						local objectAngles = CFrame.Angles(0, math.rad(rotAmount), 0)

						preview:SetPrimaryPartCFrame(objectCFrame * objectAngles)
					end
				end)
1 Like

You’d want to use the math.round() function for this. If you want it to snap to a bigger “grid” than 1x1x1, then you’d do something like:

local function snapNumber(x: number, snap: number)
	return math.round(x / snap) * snap
end
local function snapVector(vector: Vector3, snap: number)
	return Vector3.new(
		snapNumber(vector.X, snap),
		snapNumber(vector.Y, snap),
		snapNumber(vector.Z, snap)
	)
end

By the way,

preview:SetPrimaryPartCFrame(objectCFrame * objectAngles)

:SetPrimaryPartCFrame was deprecated and replaced by :PivotTo. They act basically the same, though.

3 Likes

Just use the search bar up top.
I tried with your exact title “snapping player objects to stud grid” and found a few results.
Try other terms like “building game placement” or similar.

2 Likes

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