Need help with part grabber

With my current script, clicking on an object will cause it to move to the mouse’s position, but that mostly leads to it flying way off into the distance. How do I make it so the part only hovers a couple studs from the player, and not flying into the void?

local script:

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

local SelectedPart


Mouse.Button1Up:Connect(function()
	SelectedPart = nil -- Unselect part when the player releases their mouse
end)


Mouse.Button1Down:Connect(function()
	
	local target = Mouse.Target
	
	if not target then return end -- Check if there is a target 
	if not target:IsDescendantOf(workspace.GrabbableParts) then return end -- Check if target is a descendant of the folder
	
	SelectedPart = target
	
end)


Mouse.Move:Connect(function()
	
	local MousePositionIn3DSpace = Mouse.Hit.Position -- A vector3 containing the coordinates of the mouse's position in 3D space (aka Workspace)
	
	if not SelectedPart then return end -- Check if the player is currently grabbing a part
	
	SelectedPart.Position = Vector3.new(MousePositionIn3DSpace.X, .5, MousePositionIn3DSpace.Z)
	
end)
1 Like

Try using TweenService to make it actually go into the position of the mouse, if it still doesn’t work try using CFrame for the SelectedPart

1 Like

or just loop move the part to the mouses location.

1 Like

The part moves to the mouse’s location, but usually it flies into the void. How do I limit how far it can travel from the player?

1 Like

Like @Mat_Devv said, you can also use a loop:

repeat

--code

until selectedPart.Position = Vector3.new(--stuff)

Check the Magnitude and if it is more/equal to lets say 20 studs, you can Destroy the part or just stop it. I suggest using a connection for this so its easier to disconnect

1 Like

I also wanted to make a more physics based system, so even when the object is moving it can still interact with other mediums instead of clipping through them

Just make it CanCollide and if it touches another moving part fling both of them or something using BodyVelocity.

1 Like

I am just going to attempt to rewrite the script with the points you all have given me.