It feels like this is the easiest task that LUA could do, but somewhy I just cannot figure it out. I believe the easiest way would be listing the found HumanoidRootParts magnitudes in an array, then using math.min() to find the least argument. But how to create this array? Or is there a simpler way?
This is what I have; Searches through workspaces models, finding HumanoidRootParts, then calculating the magnitudes between player and found HumanoidRootParts. How to make the code find out which of the parts is closest?
descendants = game.Workspace:GetDescendants() for index, descendant in pairs(descendants) do if descendant.ClassName == "Model" then local keppi = descendant:FindFirstChild("HumanoidRootPart") if keppi then local magnitude = (player.Character.HumanoidRootPart.Position - keppi.Position).magnitude if magnitude <= 20 and magnitude >= 1 then print(keppi.Parent.Name.." is close as heck") foundtarget = keppi end end end end
Thanks in advance!
Solution:
--foundtarget = player.Character.Head --local bestmagn = 20 local descendants = game.Workspace:GetDescendants() for index, descendant in pairs(descendants) do if descendant.ClassName == "Model" then local keppi = descendant:FindFirstChild("HumanoidRootPart") if keppi then local magnitude = (player.Character.HumanoidRootPart.Position - keppi.Position).magnitude if magnitude <= 20 and magnitude >= 1 then print(keppi.Parent.Name.." is close as heck") --if magnitude <= bestmagn then --print("better solution found") --bestmagn = magnitude --foundtarget = keppi end end end end end
Added parts commented in above script. With the help of TheeDeathCaster and Cabbler, I added a value that changes if any of the nearby parts are closer than the required 20, in the meanwhile it stores the best magnitudes parent to foundtarget value, which is then later used in code.
This would be better done using Players, not workspace.
That check is bad because it excludes anyone who isn't close as heck!!
If you want a list of sorted values you should do table.sort with a custom function. Otherwise you should simply keep track of the best values.
local function getClosestPlayer(fromPlayer) local pos0=fromPlayer.Character.PrimaryPart.Position local bestv,mag,bestp = math.huge,0,nil for _,p in ipairs(game:GetService("Players"):GetPlayers()) do if p.Character and p.Character.PrimaryPart and p~=fromPlayer then mag = (p.Character.PrimaryPart.Position-pos0).Magnitude if mag<bestv then bestv = mag bestp = p end end end return bestp end