I'm making a build tool that creates parts wherever you click in the world. Thes script makes the parts do not pass trough each other, but, sometimes,if you put a part between two parts that are so together the part will pass through the other parts and i'd like to know how to make a placement grid to make the parts line up.
Here's a picture to help you understand my problem.
Here's the scripts.
-- Local script in the tool local Event = game:GetService("ReplicatedStorage"):WaitForChild("PartsFromTool") local equipped = false script.Parent.Equipped:Connect(function(mouse) equipped = true game:GetService("UserInputService").InputBegan:Connect(function(input, g) if (equipped == true) then if (input.UserInputType == Enum.UserInputType.MouseButton1) then local position = mouse.Hit Event:FireServer(position) end end end) end) script.Parent.Unequipped:Connect(function() equipped = false end) -- Server Script in ServerScriptService game:GetService("ReplicatedStorage"):WaitForChild("PartsFromTool").OnServerEvent:Connect(function(player, position) local PCreated = Instance.new("Part") PCreated.Parent = game.Workspace PCreated.Size = Vector3.new(3, 3, 3) PCreated.Material = "Brick" PCreated.BrickColor = BrickColor.new("Persimmon") PCreated.CFrame = CFrame.new(position.Position) * CFrame.Angles(0, 0, 0) wait(0.001) PCreated.Anchored = true PCreated.CFrame = CFrame.new(PCreated.Position) * CFrame.Angles(0, 0, 0) end)
To snap to a grid you need to do a bit of math. First you divide the mouse position by your grid then add 0.5 next round down or up and finally multiply by your grid. This will center the model on a grid of your choice. For rounding I will use math.floor()
this rounds down no matter the value unless it is already an int (whole number).
Here is the code for snapping to a grid:
local player = game.Players.LocalPlayer local mouse = player:GetMouse() local Part = Instance.new("Part") Part.Anchored = true Part.Parent = workspace local PosX, PosY, PosZ local Grid = 2 -- Change this to your grid size local function Snap() PosX = math.floor(mouse.Hit.X / Grid + 0.5) * Grid -- Snaps PosY = 1 -- Change this to your Y PosZ = math.floor(mouse.Hit.Z / Grid + 0.5) * Grid -- Snaps end local function Move() mouse.TargetFilter = Part -- Ignores the part Snap() Part.Position = Vector3.new(PosX, PosY, PosZ) -- Sets the position end Mouse.Move:Connect(Move)
Now I used Vector3.new()
but you will want to use CFrame's
.
Hope this works!