How do I move a part correspondingly to workspace using mouse

So im trying to make a part placing system where you enable the tool and a green 1 stud part appears. Where you move the mouse over the workspace like hover the mouse over that stud the green one will be on that stud then when you left click a real part appears there. So I want to know how I can place parts to where the mouse is over. Its hard to explain so hopefully you get the gist thanks.

this will move a part to the mouse’s position

local mouse = game:GetService("Players").:LocalPlayer:GetMouse()

while game:GetService("RunService").RenderStepped:Wait() do
     part.CFrame = CFrame.new(mouse.Hit.p)
end

Sick thanks but is there a way where it wont just move freely but like lock to a stud?

yeah try this

local snapIncriment = 5

local mouse = game:GetService("Players").LocalPlayer:GetMouse()

local function roundtonearest(x)
     return snapIncriment * math.floor(x / snapIncriment + 0.5)
end

while game:GetService("RunService").RenderStepped:Wait() do
     local mPos = mouse.Hit.p
     part.Position = Vector3.new(round(mPos.X), round(mPos.Y), round(mPos.Z)) + Vector3.new(0, part.Size.Y/2, 0)
end
1 Like

yes thanks :slight_smile:

1 Like

but also half the part goes through the floor how would I fix that?

owait forgot about that lol. I just fixed it

1 Like

ok i just updated it and now it works with a customizable snap incriment. Enjoy!

1 Like

Your a life saver thank you very much

1 Like

Sorry to bug you again but ive been trying to clone the part in a script for tool activated but for some reason the cloned part wont got to the same position on the stud part of when it goes to mouse. Why wont it go to the position?

image

lol sorry didnt see this
well its probably because you dont actually change the position at all, you are setting a part’s clone position to the same parts position
what you should do is this

script.Parent.Activated:Connect(function()
     local cloned = script.Parent.Stud:Clone()
     cloned.Parent = workspace
end)

then in the local script write this

local snapIncriment = 5

local mouse = game:GetService("Players").LocalPlayer:GetMouse()

local function roundtonearest(x)
     return snapIncriment * math.floor(x / snapIncriment + 0.5)
end

game:GetService("RunService"):BindToRenderStep("MovePart", Enum.RenderPriority.Last.Value, function()
     local part = workspace:FindFirstChild("Stud")
     pcall(function() -- i recommend pcall instead of checking if the part exists with an if statement, and that is because this checks practically 60 times a second and will error as soon as the part gets destroyed
          local mPos = mouse.Hit.p
          part.Position = Vector3.new(round(mPos.X), round(mPos.Y), round(mPos.Z)) + Vector3.new(0, part.Size.Y/2, 0)
     end)
end)