Check if player is far away from a part?

Hello, I have been trying to make a part that when you touch opens a UI element but if you walk away from it it closes, the opening part is easy and it works fine, but for the walking away part it does not work since I am trying to make it so that when the player is far away from the part the UI will close, here is my code:

local player = game.Players.LocalPlayer

while wait(.5) do
	for i, v in pairs(workspace:WaitForChild('Rings'):GetChildren()) do
		if v:IsA('Model') then
			if (player:DistanceFromCharacter(v.PrimaryPart.Position) > 5) then
				for i, v in pairs(player.PlayerGui.MainUI.Shops:GetChildren()) do
					if v:IsA('Frame') then
						v:TweenSize(UDim2.new(0,0,0,0),nil,nil,.5)
					end
				end
			end
		end
	end
end

But it does not work since it keeps on closing it.
How do I fix this?

local distance = (chr.HumanoidRootPart.Position - part.Position).Magnitude

Then you can check the difference with an if statement.

if distance > yourmaxdistancehere then
3 Likes

One way you can achieve this is by using Magnitude to check how far the player’s character is from the part. An example of how to do this (adapted from your existing code) that should work can be seen below.

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait() -- wait for the player's character to load
local maxDistance = 5 -- how many studs away should the player be able to get before the UI closes?

while wait(.5) do
    for i,v in pairs(workspace:WaitForChild("Rings"):GetChildren()) do
        if v:IsA("Model") then
            local characterPosition = character:WaitForChild("HumanoidRootPart").Position
            local distance = (v.PrimaryPart.Position - characterPosition).Magnitude
            
            if distance >= maxDistance then
                for i, v in pairs(player.PlayerGui.MainUI.Shops:GetChildren()) do
					if v:IsA("Frame") then
						v:TweenSize(UDim2.new(0,0,0,0),nil,nil,.5)
					end
				end
            end
        end
    end
end
1 Like