Finding the closest object to a player

local closestObject = nil
local closestDistance = nil
RunService.Heartbeat:Connect(function()
	for _, Part in pairs(game.Workspace.items:GetChildren()) do
		local distance = (Part.Handle.Position - c.HumanoidRootPart.Position).Magnitude
		if distance <= 10 then
			db = true
			
			print("Closest object is ".. closestObject.Name)
		end
	end
	db = false
end)

So I’m trying to make a script where you pick up items when you click F. But I need to find the closest item so I can show the GUI and only pickup that item. Currently I have this but it’s probably not close at all. Any tips?

3 Likes

I don’t believe you actually defined closestObject, the script most likely still thinks it’s nil

It’s pretty close. You just need to add a line to compare against the current closest object.

Not sure what “db” is.

Also it’s easier if you start with

local closestDistance = math.huge

so that your first iteration doesn’t have to nil check:

local distance = --...
if distance <= 10 and distance < closestDistance then
    closestDistance = distance
    closestObject = Part
end

Also you don’t actually have the solution until the end of your loop (before the last end))

2 Likes

Yes, but what this does is the distance is going to get lower and lower and if, for example:

I go next to object 1. closest distance is 5.
Then I go next to object 2. closest distance decreases to 3.
If i go next to object 1 again but I am more than 3 away from it, it will not detect as the closest distance is 3.

I found something that will work everywhere:

local function findClosestPart(group, position)
	local closestPart, closestPartMagnitude

	local tmpMagnitude -- to store our calculation 
	for i, v in pairs(group:GetChildren()) do
		if closestPart then -- we have a part
			tmpMagnitude = (position - v.Handle.Position).magnitude

			-- check the next part
			if tmpMagnitude < closestPartMagnitude then
				closestPart = v
				closestPartMagnitude = tmpMagnitude 
			end
		else
			-- our first part
			closestPart = v
			closestPartMagnitude = (position - v.Handle.Position).magnitude
		end
	end
	return closestPart, closestPartMagnitude
end
17 Likes

this was very helpful, thank you

2 Likes