How to snap position relative to a part?

I know how to snap a position but how do I do it relative to a part that I am hovering over?
Its like how in studio, dragging a part onto a part snaps it relative to it.

Snap script:

local function SnapToGrid(value)
	if type(value) == "number" then
		return math.round(value * gridSize) / gridSize
		
	elseif type(value) == "vector" then
		return Vector3.new(SnapToGrid(value.X), SnapToGrid(value.Y), SnapToGrid(value.Z))
	end
end

local relativePosition = SnapToGrid(mouse.Hit.Position)
1 Like

First, calcuate the relative offset of the point you want snapped to the Part/CFrame you want it aligned to. Then align this offset. Finally, multiply the aligned offset by the origin of the Part/CFrame you want the snapping to be relative to.

Using the code you provided, it might look something like this:

local plate = workspace.Plate --Assume this is a Part that you want to snap relatively to
local relativeOffset = plate.CFrame:PointToObjectSpace(mouse.Hit.Position)
local alignedOffset = SnapToGrid(relativeOffset)
local snapPosition = plate.CFrame * alignedOffset --This is the relatively aligned snapping Vector3
1 Like

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