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

How do I make it so when I click an part with a script inside of it, it will follow my mouse?

I don't know how I would do this, I want it to be like when you grab a piece of dough in Work at a Pizza Place. When I click a part, I want it to follow my cursor until I click again. Any idea of how I could do this? This isn't a request, I genuinely don't know how to do this.

1 answer

Unsure if this works outside of studio. Requires a ClickDetector in the part.

local detector = script.Parent.ClickDetector
local following = false	--Used to stop others from clicking
local leader = nil	--Parent of mouse that clicked the detector
local stopFunc = nil

local runService = game:GetService("RunService")	--Recommend this over while loops

function followPlayer()
	local mouse = leader:GetMouse()
	local hit = mouse.Hit
	local yAnchor = leader.Character:FindFirstChild("HumanoidRootPart").Position.Y	--Prevents dough from bouncing towards the screen
	
	if hit then
		script.Parent.Position = Vector3.new(hit.p.X,yAnchor,hit.p.Z)
	end
end
function stopFollow()
	runService:UnbindFromRenderStep("moveDough")
	
	following = false
	script.Parent.Anchored = false
	script.Parent.CanCollide = true
	leader = nil
	if stopFunc then
		stopFunc:disconnect()
		stopFunc = nil
	end
end

function onClick(ply)
	if not following then
		following = true
		script.Parent.Anchored = true
		script.Parent.CanCollide = false
		leader = ply
		local mouse = leader:GetMouse()
		runService:BindToRenderStep("moveDough",0,followPlayer)
		stopFunc = mouse.Button1Down:connect(stopFollow)
	end
end
detector.MouseClick:connect(onClick)

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