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

Getting objects within a certain distance from another object?

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

✓ Accepted answer

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

5 comments

0

Thanks! I never thought of using magnitude! Also, will constantly searching the workspace lag the game a lot?

0

optimized. get all parts once, add/remove parts when parts are added/removed.

0

Thanks again.. might I ask what just happened though? X|

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.

0

Oh, ok. I was just asking about the meaning of the stuff you changed. Thanks for the help! :D

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