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?
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:
1 | local player = game.Players.Player 1 |
2 | local radius = 5 |
3 |
4 | if player:DistanceFromCharacter(Vector 3. new( 1 , 433 , 656 )) < radius then --Vector3 can be the Position property of a part if you want. |
5 | print ( 'player is within radius' ) |
6 | end |
The other technique involves the use of some simple vector math:
1 | local position 1 = Vector 3. new( 12031 , 13123 , 3123 ) |
2 | local position 2 = Vector 3. new( 12031 , 3123 , 13123 ) |
3 |
4 | local distance = (position 1 - position 2 ).magnitude |
5 |
6 | --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.
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)
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:
1 | distanceThreshold = 10 |
2 | distance = (player 1. Character.Torso.CFrame.p - player 2. Character.Torso.CFrame.p).Magnitude |
3 | if distance < distanceThreshold then |
4 | --Do something for close proximity |
5 | end |
... and as JuHDude suggests, read the article on Magnitude, but I also recommend reading about the Vector3 type in general.