Moving a part when holding it

Hey Guys I made a script that when I hold my mouse on a part, it will move, but it’s a bit buggy and kind of doesn’t move with my mouse perfectly, and it’s also clipping the parts.

Script:

local Heartbeat = game:GetService("RunService").Heartbeat
local UserInputService = game:GetService("UserInputService")

local ScriptingsFolder = game.Workspace:WaitForChild("Scriptings")
local EarthPart = ScriptingsFolder:WaitForChild("Earth")
local ClickDetector = EarthPart:WaitForChild("ClickDetector")

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

local isHovering = false
local isHolding = false
local RunMove = false
local initialOffset = nil

ClickDetector.MouseHoverEnter:Connect(function()
	isHovering = true
end)

ClickDetector.MouseHoverLeave:Connect(function()
	isHovering = false
end)

UserInputService.InputBegan:Connect(function(input, processed)
	if not processed and input.UserInputType == Enum.UserInputType.MouseButton1 and isHovering then
		isHolding = true
	end
end)

UserInputService.InputEnded:Connect(function(input)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		isHolding = false
		RunMove = false
	end
end)

Heartbeat:Connect(function()
	if isHolding then
		local newPosition = mouse.Hit.Position
		if not initialOffset then
			initialOffset = EarthPart.Position - newPosition
		end

		EarthPart.Position = newPosition + initialOffset
	else
		initialOffset = nil
	end
end)

Any Solution?

2 Likes