Fixing my simple grid system

Hello, I have been working on a grid system for my placement game.

This is my code, I want the object to be positioned exactly in 4 stud increments.

game:GetService("RunService").RenderStepped:Connect(function() 
     local mousePos = mouse.Hit.Position
				if math.floor(mousePos.X) % 4 == 0 then
					object_position = Vector3.new(math.floor(mousePos.X), 0, math.floor(mousePos.Z))
				elseif (math.floor(mousePos.X) + 1) % 4 == 0 then
					object_position = Vector3.new(math.floor(mousePos.X - 1), 0, math.floor(mousePos.Z))
				elseif (math.floor(mousePos.X) - 1) % 4 == 0 then
					object_position = Vector3.new(math.floor(mousePos.X + 1), 0, math.floor(mousePos.Z))
				end
				
				placement_object:SetPrimaryPartCFrame(CFrame.new(object_position) * CFrame.Angles(0, math.rad(rotation), 0))
			end
		end
	end
end)
1 Like

Replace that big if statement for this (discluding the function & constant(GRID_SNAP), put that wherever you want in your code):

local GRID_SNAP = 4

local function round(num : number, toNearest : number) : number
   return math.round(num / toNearest) * toNearest
end


object_position = Vector3.new(
    round(mousePos.X, GRID_SNAP),
    round(mousePos.Y, GRID_SNAP),
    round(mousePos.Z, GRID_SNAP)
)

Think this will work but I haven’t checked