Hey, I use the following script to snap my model to a grid:
function PlacementUtilities.snapToGrid(CFramePosition, grid, studs, rotation, modelSize)
-- Unit Vectors for the grid's local axes
local back = Vector3.new(0, -1, 0)
local top = Vector3.new(0, 0, -1)
local right = Vector3.new(-1, 0, 0)
-- Rotates the grid size to match the actual rotation of the grid.
local gridCFrame = grid.CFrame * CFrame.fromMatrix(-back*grid.Size/2, right, top, back)
-- Convert the model CFrame to grid space and gets the grid size rotation so we can match that to the model.
local gridSpaceCFrame = grid.CFrame:ToObjectSpace(CFramePosition)
local gridRotationSize = Vector2.new((grid.Size * right).magnitude, (grid.Size * top).magnitude)
-- Rotate the size of model to match to surface.
local fixedSize = CFrame.fromEulerAnglesYXZ(0, math.rad(rotation), 0) * modelSize
fixedSize = Vector3.new(math.abs(fixedSize.X), math.abs(fixedSize.Y), math.abs(fixedSize.Z))
-- Distance from center for clamping the model to the edges of the grid.
local distanceSize = (Vector2.new(gridRotationSize.X,gridRotationSize.Y) - Vector2.new(fixedSize.X, fixedSize.Z))/2
-- CLAMPING
local X, Z
if BuildSystem.Clamping then
X = math.clamp(gridSpaceCFrame.Position.X, -distanceSize.X, distanceSize.X)
Z = math.clamp(gridSpaceCFrame.Position.Z, -distanceSize.Y, distanceSize.Y)
else
X = gridSpaceCFrame.Position.X
Z = gridSpaceCFrame.Position.Z
end
-- Snap each component of the grid space position to the grid
local snappedGridSpacePosition = Vector3.new(
math.sign(X) * (math.abs(X) - math.abs(X) % studs) + (distanceSize.X % studs),
gridSpaceCFrame.Position.Y,
math.sign(Z) * (math.abs(Z) - math.abs(Z) % studs) + (distanceSize.Y % studs)
)
-- Convert the snapped grid space position back to world space
local snappedWorldSpacePosition = grid.CFrame:PointToWorldSpace(snappedGridSpacePosition)
-- Return the adjusted position as a CFrame
return CFrame.new(snappedWorldSpacePosition)
end
As well as snapping to the grid, it ensures the model cannot exit the grid - but this particular feature has a minor issue.
Normal / Intended:
→ You face where it’s going to spawn.
The Bug
→ When facing this particular side, the clamping means I can’t place on the edge:
Would appreciate any help on why / how I can fix. Thank you in advanced!