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?
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.
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