Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can i make a 3D grid snapping and placement script?

1 answer

✓ Accepted answer

You will need to get set up first. Create a Model with a PrimaryPart. You can assign a PrimaryPart by clicking PrimaryPart in the properties menu. Then click on the object you want to be the PrimaryPart either in the explorer or the game view. You will want to put a LocalScript in a client side service such as StarterGui or ReplicatedFirst (I have mine in StarterGui and it works fine). Here is a basic grid system example:

local Model = workspace.Model -- Or where ever you have it
local GridSize = 2 --Or whatever size you want in studs

local Player = game.Players.LocalPlayer
local Mouse = Player:GetMouse()

Mouse.Move:Connect(function() -- fired when the mouse moves
	Mouse.TargetFilter = Model -- Ignores the model
	-- math.floor rounds down no matter how large the number is
	-- This means even if you had 1.9 it would round down to 1.
	
	-- Snap to grid
	local PosX = math.floor(Mouse.Hit.X / GridSize + 0.5) * GridSize
	local PosY = Mouse.Hit.Y
	local PosZ = math.floor(Mouse.Hit.Z / GridSize + 0.5) * GridSize
	
	--Moves the Model
	
	Model:MoveTo(Vector3.new(PosX, PosY, PosZ))
	-- if you don't want to move on the Y then use
	-- SetPrimaryPartCFrame instead of MoveTo
end)

Mouse.Hit.axis is your mouse position on that axis. MoveTo moves the model to a Vector3 value. As for the rounding it centers it with in the grid of 2 studs which you can change by changing the GridSize variable.

If you just want the grid to be 1x1x1 then an even simpler solution is required:

PosX = math.floor(Mouse.Hit.X) -- Just did it for one axis
-- This will make the part move on a 1 stud grid.

As for placing goes there is an event that you can use. Mouse.Button1Down should work. Example:

Mouse.Button1Down:Connect(function()
	local PlacedModel = Model:Clone() -- Creates a clone of the current model
	Model:Destroy() -- Destroys the moving model

	-- Stop placement code below

	-- Thats for you to do
end)

Hopefully this helps!

2 comments

0

does the primary part have to be a certian size or just any size

0

I would make it a little bigger than the model.

This discussion is preserved as it was. New answers, comments, and votes are closed.