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

Getting objects within a certain distance from another object?

Asked by 8 years ago

So I've nearly torn the wiki apart (metaphorically) trying to find a way to do this. What I want to do is get/define all the parts within a certain distance from another part, and use them in a variable. I have the code all worked out, problem is how do I select those parts? CFrame? Method I might not know of? Math? Magic? I have the script and know how to set the distance, I just need to know how to define/get/select the parts. Is there a way to do this? Any help is appreciated. :)

P.S. Let me know if this is confusing, I'm not sure if I worded some of this right. Thanks!

1 answer

Log in to vote
1
Answered by
1waffle1 2908 Trusted Badge of Merit Moderation Voter Community Moderator
8 years ago

To find all of the parts within a radius of a point, iterate through workspace recursively:

function getparts(point,radius)
    local list={}
    local f;function f(x)
        for _,v in pairs(x:GetChildren())do
            f(v)
            if v:IsA("BasePart")and(v.Position-point).magnitude<=radius then
                list[#list+1]=v
            end
        end
    end
    f(workspace)
    return list
end

to select them in studio, game.Selection:Set(getparts(point,radius))

If you're worried about efficiency for constant scanning, here's an optimization:

local allparts={}
do
    local f;function f(x)
        for _,v in pairs(x:GetChildren())do
            f(v)
            if v:IsA("BasePart")and v.ClassName~="Terrain"then
                allparts[v]=true
            end
        end
    end
    f(workspace)
end
workspace.DescendantAdded:connect(function(x)
    if x:IsA("BasePart")then
        allparts[x]=true
    end
end)
workspace.DescendantRemoving:connect(function(x)
    if x:IsA("BasePart")then
        allparts[x]=false
end)
function getparts(point,radius)
    local list={}
    for v,_ in pairs(allparts)do
        if(v.Position-point).magnitude<=radius then
            list[#list+1]=v
        end
    end
    return list
end
0
Thanks! I never thought of using magnitude! Also, will constantly searching the workspace lag the game a lot? AwsomeSpongebob 350 — 8y
0
optimized. get all parts once, add/remove parts when parts are added/removed. 1waffle1 2908 — 8y
0
Thanks again.. might I ask what just happened though? X| AwsomeSpongebob 350 — 8y
0
i don't know what you're asking. If you get all of the parts and track when the existing parts changes, you don't have to go back and find them again every time you want to iterate through them. 1waffle1 2908 — 8y
0
Oh, ok. I was just asking about the meaning of the stuff you changed. Thanks for the help! :D AwsomeSpongebob 350 — 8y
Ad

Answer this question