# How to find players within a certain distance of my character?

I am pretty sure its magnitude, pretty much I need to know how to find out in my code how many players are within a certain distance of my character then find the closest one all the way to my furthest one from me, each distance depending on how many there are will have different effects but without our right giving me the code what would be the best way of achieving this, because id like to do it on my own, I just need pointed in the right direction.

Yes, you can use (Vector3-Vector3).magnitude to get the distance between two players’ HumanoidRootParts. Think through each step of the problem and how you could solve it.

1. Loop through all players (aside from your own)
2. Store the distance from their HumanoidRootPart to yours in an array; Perhaps structure the table elements like `{player, distance}` just so you know which elements point to which player
3. `table.sort` the table based on the second table element (the distance) of each element; the first & last elements should be the closest and furthest characters (or vice versa depending on how you sort it)
3 Likes

and everything in between will be in the correct order up until last?

That’s what table.sort does

thankyou so much i dont use tables much so I wasnt aware I could do that.

Player.DistanceFromCharacter also exists. This function is less pure Lua and passes the calculation work off to the backend. It is also future proof in the sense that if Roblox ever decides to update the rig construct of a character, they can also update the calculation point and you won’t have to worry about changing your code at all.

2 Likes