Finding The Nearest Part To A Main Part

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I Want To Find The Closest Part To Main Part To Pathfind To
  2. What is the issue? Include screenshots / videos if possible!
    I Dont Know How To Do It And I Cant Find Anything
  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    Ive Tried Looking Around But I Cant Find What I Need
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
local Char = script.Parent
repeat
	wait(0.5)
	local AllParts = workspace.Food:GetChildren()
	for i, IndividualPart in pairs(AllParts) do
		local Distance = (Char.Position - IndividualPart.Position).magnitude
		print(Distance, IndividualPart)
	end
until false

Thanks For Any Help

1 Like

Wouldn’t the code that you provided work though?

1 Like

I Need To Find The Absolue Closest Part That Just Finds A Part And Tells Me The Distance And Its Name

1 Like

It Might Work And I Dont Realize it tho just tested it it doesent

1 Like

I see. Maybe something like this should work?

local greatestDistance
local farthestPart
	for i, IndividualPart in pairs(AllParts) do
		local Distance = (Char.Position - IndividualPart.Position).magnitude
		if Distance > greatestDistance then
                     greatestDistance = Distance
                     farthestPart = IndividualPart
                end
	end

farthestPart blah blah code
1 Like

The Problem With That Is Distance Is A Vector3 Value

1 Like

Try using .Magnitude. I don’t know if it matters what the capital letter is though. BUT magnitude actually returns a number, not vector3

1 Like

The Magnitude member of a Vector3 returns the size as a single number.

1 Like

Maybe, but I’m sure that if you use the (Pos1 - Pos2).Magnitude it returns the distance. In fact, I just used it yesterday!

1 Like

tried your code didnt work but i might have an idea

1 Like

Is there any errors? Or anything? In the output I mean

1 Like

ill tell you it i thought i had a solution
its that you cant compare a number to nil

MB

1 Like

Oh yeah. It has to be
local greatestDistance = 0
Just add that to the top thing where it says
local greatestDistance
And it should work

1 Like

Just so ya know this is backwards i need closest distance to pathfind to

1 Like

Ohhhhh whoops
Change the Distance > greatestDistance
into a <

2 Likes

i alr fliped it and fixed it Tysm For the help im not verry flamiliar w/ i loops

2 Likes

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