Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How do you make a radius player detection?

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

✓ Accepted answer

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.

2 comments

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?

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.

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.

This discussion is preserved as it was. New answers, comments, and votes are closed.