How to check if a player is next to a part?

Hi there! So I want to make a script That allows the player to drag parts. It works BUT I want to add a range.
Example, if the player is 5 studs away he can drag the part.
is there something I can use?

The script:

while true do
	wait()
	if Mouse.Target ~= nil then
		if Mouse.Target:FindFirstChild("CanDrag") ~= nil then
			print("drag")
		else
			print("No drag")
		end
	end
	if Dragger.Weld.Part1 ~= nil then
		RotY = RotY + Y
		RotX = RotX + X
		CF1 = CFrame.new(Player.Head.CFrame.Position, Vector3.new(Mouse.Hit.X, Mouse.Hit.Y, Mouse.Hit.Z))
		CF2 = CF1 * CFrame.new(0, 0, -4)
		Dragger.BPos.Position = Vector3.new(CF2.X, CF2.Y, CF2.Z)
		Dragger.BGyro.CFrame = game.Workspace.CurrentCamera.CFrame * CFrame.Angles(math.rad(RotY), math.rad(RotX), 0)
	end
end
2 Likes

You can get the magnitude between the part you want to drag and the rootpart of the character and if it’s less than 5 then drag the part.

local Distance = (Part.Position - RootPart.Position).Magnitude
if Distance <= 5 then
    -- drag part
end
3 Likes

You can use Magnitude (aka :DistanceFromCharacter() in this case)

if (playerInstance:DistanceFromCharacter(PART_POS)) < 5 then --returns Magnitude or the length of the distance for the character and part
   --player is less than 5 studs of object so DRAG_PART
else
   --player is greater than 5 studs of object so not DRAG_PART
end

--or if you want the hard way
--i assume you already got the humanoidrootpart

if (HumanoidRootPart.Position - PART_POS).Magnitude < 5 then
   --drag part
end

Info on DistanceFromCharacter:
here

This is just a little bit optimised version of @heII_ish 's script

local Part = game.woskpace.Part --change this
local RootPart = game.Players.LocalPlayer.HumanoidRootPart --change this as well, if you prefer
local Distance = (Part.Position - Vector3.new(RootPart.Position.X,Part.Position.Y,RootPart.Position.Z)).Magnitude
if Distance <= 5 then
    -- drag part
end

i made the altitude of the root part to equal to the altitude of the part so you get the Exact distance from the part.

I am not trying to do a specific part, I want to drag the parts that have the Value CanDrag in them.

It almost works. But, when you are not in the rang and try to pick something up it floats