How do I make a gui visible if a player is within 4 studs of a recycling bin

Hi, i’m trying to make a gui show up when a player is 4 studs away from a recycling bin. I don’t want to use .Touched as its very unreliable. Is there any way I could achieve this with Region3? if so please provide some example code. Thanks , and Merry Christmas!

I don’t know a lot about Region3, but you can use the Player:DistanceFromCharacter() property to check the distance between the Player’s character and the part.

Example: (LocalScript)

-- variables

local RunService = game:GetService('RunService'); -- run service
local Player = game.Players.LocalPlayer; -- the player
local Part = game.Workspace.Part; -- in your case, recycling bin

local maxDistance = 15; -- the max distance for the gui to show up

RunService.RenderStepped:Connect(function()
     if Player:DistanceFromCharacter(Part.Position) <= maxDistance then
          -- code to execute if the player is near the part, make sure to check if the gui already exists to prevent spam
     else
         -- code to execute if not near the part/remove the gui
end)

That’s the best I can think of, Merry Christmas!

You could use the .Magnitude property of the Vector3 value to determine the distance between the player’s character and the recycling bin. In this example I will use the character’s primary part’s position, or the HumanoidRootPart.

local Run = game:GetService("RunService")
local recycling_bin = your.recycling.bin
local interactDistance = 4

local Player = game:GetService("Players").LocalPlayer

Run.Stepped:Connect(function()
     local Character = Player.Character or Player.CharacterAdded:Wait()
     local Root = Character:WaitForChild("HumanoidRootPart")
     local Magnitude = (Root.Position - recycling_bin.Position).Magnitude
     if Magnitude <= interactDistance then
         -- open gui if closed
      else
         -- close gui if open
     end
end)

@moodyqz suggests a great answer above, but :GetDistanceFromCharacter uses the head as a reference point, and so the distance may be slightly closer than it appears. Still a good option here :+1:

2 Likes

Extra note: It’s not only used to determine distances between player character and parts, but it can also be used for all BasePart type instance.

3 Likes

It can be used with any two Vector3 values, doesn’t have to be a basepart specifically but that’s probably the most common usage.

2 Likes