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

Best way to check if a player is within radius of something?

Asked by 5 years ago

I need the best way, that is, the way that will put the least load on the client, since I'm planning on doing this client-side.

I need to check if the player is within range of anything that is labeled as "loot". That means that it's a lot more than one thing that I need to check if the player is within range of.

I've read things that say an endless while loop will do, but I was planning on doing the checks in a RenderStepped function. Is this the best place to do the checks? Again, I'm not checking if the player is within range of just one thing. I need to check if the player is within range of anything on the map labeled loot.

0
I think an endless loop that runs maybe 5 or 10 times a second would suffice theCJarmy7 1293 — 5y
0
Yeah, I guess there's no reason to do it every frame. dunkmaster452 1 — 5y

1 answer

Log in to vote
2
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

First, I would use a Region3 to detect the objects within the player's area, to limit the number of parts that the client searches through. For example, this function would create a Region3 "box" that is 10 studs wide around the position it is given:

local RegionSize = 10

local function MakeRegion(Pos)
    return Region3.new(Pos - Vector3.new(1,1,1)*(RegionSize/2), Pos + Vector3.new(1,1,1)*(RegionSize/2))
end

Then, every 0.1 seconds (or whatever delay you desire), you could iterate through the parts detected in the box, and check their magnitude to the character (checking the magnitude would make the detection spherical rather than a cube):

while wait(0.1) do
    local Reg = MakeRegion(Character.HumanoidRootPart.Position)
    local Parts = workspace:FindPartsInRegion3(Reg,Character,math.huge) --ignore parts from the character
    for _,Part in pairs(Parts) do
        if Part.Name == "loot" then
            if (Part.Position - Character.HumanoidRootPart.Position).magnitude <= RegionSize/2 then
                print("loot is within 5 studs of the character")
            end
        end
    end
end

So basically, the Region3 would reduce the number of parts you iterate through to just the parts around the character, and the magnitude would check if the detected parts are within the radius of the character.

Hope this helps!

0
Thanks for the answer, definitely will try. dunkmaster452 1 — 5y
Ad

Answer this question