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

How do you make a radius player detection?

Asked by 10 years ago

I was wondering if there is a way to detect if there is a player within a custom radius. I'm currently using invisible bricks and the Touched Event, but I don't think this is the best way. I've searched on Roblox Wiki and couldn't find anything :(

Any suggestions?

3 answers

Log in to vote
9
Answered by
m0rgoth 75
10 years ago

There are two ways to check for a distance in roblox that I usually use for this sort of thing. The first is a method of the roblox Player object:

local player = game.Players.Player1
local radius = 5

if player:DistanceFromCharacter(Vector3.new(1,433,656)) < radius then       --Vector3 can be the Position property of a part if you want.
    print('player is within radius')
end

The other technique involves the use of some simple vector math:

local position1 = Vector3.new(12031,13123,3123)
local position2 = Vector3.new(12031,3123,13123)

local distance = (position1 - position2).magnitude

--You can use this distance to check for the range the same way as you do with the first method.

Basically, I use the first option when I am checking for distances with a player, and have access to the player, and I use the second option when I am just checking distances between random objects or I do not have access to the player.

1
That would solve the main part of my problem. I still need to be constantly testing if the player is within or not the radius. I want to make interactive objects that shows the message "press E to interact" whenever the player is close to it, so i tought of using a while loop or the "Changed" event on the player's Torso that would test for close objects every time the Position changes. Any ideas? Mattews123 20 — 10y
0
Your ideas are the exact solutions I would suggest. Either the infinite loop or the changed event. The changed event causes much less lag however, so that would be the best option imo. m0rgoth 75 — 10y
Ad
Log in to vote
1
Answered by
JuHDude 25
10 years ago

You could always use Magnitude, to see if the player is with-in a certain radius.

I recommend reading this part of the Wiki: (http://wiki.roblox.com/index.php/Magnitude)

Log in to vote
0
Answered by
duckwit 1404 Moderation Voter
10 years ago

If you have a reference to each player, say for example player1 and player2, you can compare the distance between them with a threshold like-so:

distanceThreshold = 10
distance = (player1.Character.Torso.CFrame.p - player2.Character.Torso.CFrame.p).Magnitude 
if  distance < distanceThreshold then
--Do something for close proximity
end

... and as JuHDude suggests, read the article on Magnitude, but I also recommend reading about the Vector3 type in general.

Answer this question