How do you make a part follow the mouse?

Hello! I’m trying to make a script that will make a part follow your mouse when you move your mouse around (in the sense of dragging it without needing to click).
Currently I’m having issues figuring it out because I’m new to scripting and just can’t figure out what I’m doing wrong.
I’ve tried a bunch of different ways of going about it but none of them have worked so far, I’ve also looked to see if there was any other topics similar to mine but couldn’t find any that helped.
This is what I currently have right now, it is a LocalScript inside of a Part.

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


rs.RenderStepped:Connect(function()
	local part = script.Parent
	if mouse.Move then
		part.Position = Vector3.new(mouse.X, 0, mouse.Z)
	end
end)
4 Likes

Hey! You need to get the position of the mouse with Mouse.Hit.Position.

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


rs.RenderStepped:Connect(function()
	local part = script.Parent
	if mouse.Move then
		part.Position = mouse.Hit.Position
	end
end)
4 Likes

Thank you for replying with some help but it sadly still doesn’t work, at least for me, the part is still staying in place (and yes its unanchored).

1 Like

Interesting, it should work even if it’s anchored. I’m unsure then, because I know that the reason it wasn’t previously working is because Mouse.X is referring to the position in a Vector2, almost like the position of the mouse GUI rather than in the physical world space.

Give me a moment, and I’ll hop into studio to try it out.

1 Like

Oh, well as I mentioned above, I’m still new to scripting and all that jazz, so I’m very sorry for any inconveniences and I thank you a lot for helping me!

1 Like

It appears that LocalScripts don’t run inside of parts, and only really run inside of stuff that has Network Ownership (I think).

Put this in a LocalScript in StarterPlayer > StarterPlayerScripts and it should work fine : )

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

local part = workspace.Part
mouse.Move:Connect(function()
	part.Position = Vector3.new(mouse.Hit.Position.X, 0.5, mouse.Hit.Position.Z)
end)
8 Likes

Hey! It works perfectly, thank you so much dude you are amazing!

2 Likes

Local scripts don’t run when placed inside the ‘Workspace’ container.

2 Likes

Switch “local part = workspace.Part” to “local part = workspace:WaitForChild(“Part”).”

1 Like