How can I cycle through parts and find the nearest one?

I am making an agriculture system for my game, and I need a soil block to find the nearest water source, and if it is close enough, the soil will become wet.

I have a folder named “WaterParts” and parts named “WaterZone” in the folder, and I know that I need the soil to loop through the folder and check for the closest one, and then see if it is close enough to it (maybe in a 200 stud radius). The problem is that I don’t really know how to find the closest one.

I’ve tried doing magnitude stuff but I suck at magnitude and also looping through tables and stuff

Basically, the brown soil parts, I want them to find the nearest water source, and if it’s close enough, the soil becomes wet. In the photo, the two soil parts are in the proximity of the water, and it’s the closest one also, so it becomes wet. The dry soil’s nearest water source is the one of the corner, but because it’s so far from it, it is dry

Hopefully someone can help me with this, It’s been kind of a struggle, thanks
(Sorry if I did this wrong, it’s my first time actually posting and not reading on this platform)

1 Like

Something like this in your loop (Can’t open studio right now to use the editor)

local ClosestPart = nil
for each,part (your loop here) do
if ClosestPart == nil then 
ClosestPart = part  
local Distance = (SoilPart.Position - part.Position).Magnitude
local CurrentDistance = (SoilPart.Position - ClosestPart.Position).Magnitude
if Distance < CurrentDistance then ClosestPart = part end

Thank you, this helped me get an idea of what to do :grinning:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.