Opening a GUI by pressing a keyboard button when in proximity to a brick

Working on adding a class/loadout system for a game and one of the things I wish to do is open a GUI when a player presses a button on their keyboard and is in proximity to a brick.

I already know how to detect when a button is pressed using UserInputService however the being in proximity is the tricky part.

How would I go about doing this? Any other advice in regards to this would also be appreciated.

2 Likes

Use :DistanceFromCharacter() on ClientSide in StarterGui. :^)

Here’se an example of how you can check it,
if game.Players.LocalPlayer:DistanceFromCharacter(Part.Position) <= 10 then
That checks the Distance that Character is from Part.Position, and checks if it’s less than or equal to 10.

Then just listen for UserInputService.

local UserInputService = game:GetService("UserInputService")
UserInputService.InputBegan:Connect(function(InputObject, Processed)
    if InputObject.KeyCode == Enum.KeyCode.E then
	end
end)

This listens for you to press the Key ‘E’.

Combine that in a loop and you’ll get something like this,

local UserInputService = game:GetService("UserInputService")

while wait(.1) do
    UserInputService.InputBegan:Connect(function(InputObject, Processed)
        if game.Players.LocalPlayer:DistanceFromCharacter(Part.Position) <= 10 then
            if InputObject.KeyCode == Enum.KeyCode.E then
	        end
        end
end)

Hope that makes sense. :slight_smile:
Let me know if you have questions.

12 Likes

There are a variety of ways to do this, but here’s two:

  • Check the distance – (PositionA - PositionB).Magnitude – in an infinite while loop, if it is below a certain amount, enable the input stuff, if it is above, disable it
  • Use an invisible part with CanCollide set to false as a hitbox. Listen to its Touched and TouchEnded signals, and enable/disable the input stuff when the player touches and stops touching the part.

Do both on the client, don’t use the server, as latency will affect feedback.

7 Likes

Thank you both!

7 Likes