Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I detect if a player is within a certain radius?

Asked by
zomspi 541 Moderation Voter
5 years ago

I have searched everywhere, but every tutorial says I need to use magnitude, but none of them work. This is a script that didn't work and I can't figure out why?

01local UIS =  game:GetService('UserInputService')
02local plr = game.Players.LocalPlayer
03UIS.InputBegan:Connect(function(input)
04 if input.KeyCode == Enum.KeyCode.E then
05   if (plr.Character.HumanoidRootPart.Position - script.Parent.Back.Position).magnitude <= 20 then
06 
07print("yes")
08    end
09   end
10end)

Thanks!

0
.Magnitude maybe idk xd greatneil80 2647 — 5y
0
that should have worked greatneil80 2647 — 5y
0
I had it in workspace zomspi 541 — 5y

1 answer

Log in to vote
1
Answered by
TrippyV 314 Donator Moderation Voter
5 years ago

Judging by your use of script.Parent.Back.Position I assume that your LocalScript is within workspace. This would be your issue as LocalScripts cannot execute in any context outside of the Backpack, Character, PlayerGui, PlayerScripts, or the ReplicatedFirst service.

To fix this issue, simply put your script in something like StarterCharacterScripts and reference the object in a different way, like so:

(Also, a magnitude check is not needed if you are getting the distance from a player's character, as you can use the DistanceFromCharacter method of the player)

01local Back = -- Put the path of your object here
02 
03local UIS = game:GetService("UserInputService")
04local plr = game.Players.LocalPlayer
05 
06UIS.InputBegan:Connect(function(input, GPE)
07    if GPE then return end
08 
09    if input.UserInputType == Enum.UserInputType.Keyboard then
10        if input.KeyCode == Enum.KeyCode.E then
11            if plr:DistanceFromCharacter(Back.Position) <= 20 then
12                print("yes")
13            end
14        end
15    end
16end)

As a couple pointers, I've added a GameProcessedEvent check on line 7; this is entirely optional, but recommended as the event could potentially fire while the player is chatting if this check did not exist.

I've also added a UserInputType check on line 9 to prevent any errors from appearing regarding the KeyCode being nil for other types of inputs.

0
Thank you! zomspi 541 — 5y
Ad

Answer this question