How would I make a grid system

How would I make a grid system? Like you would place a block down and it would go to the nearest grid position. Maybe like rounding the position up? For like a buiding system in a farm game.

A grid-system I used awhile back may come in handy in this situation

local posX
local posY
local posZ
	 
	local gridSize = 2
	 
	local function Snap()
	    posX = math.floor(Mouse.Hit.X / gridSize + 0.5) * gridSize
	    posY = Mouse.Hit.Y -- or what ever you want
	 	 posZ = math.floor(Mouse.Hit.Z / gridSize + 0.5) * gridSize
end
local Part = -- The Part
Mouse.Move:Connect(function()
Snap()
Mouse.TargetFilter = Part
									
Part.CFrame = CFrame.new(Vector3.new(posX, Mouse.Hit.Y, posZ))*CFrame.Angles(0,math.rad(Preview.PrimaryPart.Orientation.Y),0 ))
end)

3 Likes

From my experience using math.round is better than math.floor. Here’s an example:

RunService.RenderStepped:Connect(function()
	local mousePos = mouse.Hit.Position
	local target = mouse.Target
	local surface = mouse.TargetSurface
	if target then
		local xDif = 0
		local yDif = 0
		local zDif = 0
		
		local x = 0
		local y = 0
		local z = 0

		if surface == Enum.NormalId.Top then
			yDif = 3
		elseif surface == Enum.NormalId.Bottom then
				yDif = -3
		elseif surface == Enum.NormalId.Front then
			zDif = -3
		elseif surface == Enum.NormalId.Back then
			zDif = 3
		elseif surface == Enum.NormalId.Right then
			xDif = 3
		elseif surface == Enum.NormalId.Left then
			xDif = -3
		end
		
		if target.Name == "Block" then
			x = target.Position.X + xDif
			y = target.Position.Y + yDif
			z= target.Position.Z + zDif
		elseif target.Name ~= "Block" then
			x = math.round(mousePos.X/3) * 3
			y = math.round(target.Position.Y/3) * 3 + yDif
			z = math.round(mousePos.Z/3) * 3
		end
			Block.Position = Vector3.new(x,y,z)
	end	
end)

Note I did not include the variables. It’s not working!