function findClosestPlayer(position)
local fake = nil
local children = game.Workspace:GetChildren()
local space = 30
for i, v in pairs(children) do
if v:IsA("Model") then
local h = v:FindFirstChild("Humanoid")--finds every humanoid in list separately, then sends to below h and root
if h then
local root = v:FindFirstChild("HumanoidRootPart")
if root then
if (root ~= nil) and (h ~= nil) and (h.Health > 0) then
if (root.Position - position).magnitude < space then
space = (root.Position - position).magnitude
print("work")
fake = root
end
end
end
end
end
end
return fake
end
while wait() do
local t = findClosestPlayer(part.Position)
if t ~= nil then
bodyGyro.CFrame = CFrame.new(part.Position, t.Position)
end
end
The part where it says
space = 30
and then when a humanoid is within 30 studs of the part it changes to
space = (humanoidrootpart.position - position of the part).magnitude
is this part ^ even useful if the space variable is always resetting to 30 while going through the while loop (i think). And it doesn’t check the space variable anymore? I’m so confused how this works.
The script is looking for the closest player. While it’s looping it keeps finding players that are less than the currently known closest player.
It’s setting space = (humanoidrootpart.position - position of the part).magnitude to know who currently is closest while it’s busy finding the next closest player if there is one.
As for
And it doesn’t check the space variable anymore?
It does here if (root.Position - position).magnitude < space then from the for loop it’s performing for i, v in pairs(children) do
This script uses a minimum value algorithm, where it goes through each value individually, picking the lowest one each time.
If you had a table of data such as this:
3,4,6,2,8,6,1
The algorithm would basically do this,
4>3? Yes, pick 3 as the lowest current value
6>3? Yes, 3 remains the lowest value checked
2>3? No, 2 is lower pick 2 as the lowest value
8>2? Yes, 2 remains the lowest value checked
6>2? Yes, 2 remains the lowest value checked
1>2? No, 1 is now the lowest value checked
As it goes through each part of the data, it stores the lowest value that has been checked. Your script stores this value in the variable “space” (eg. 4>3? Yes, space = 3. 2>3? No, space = 2).
By looping through each value and comparing each value to the lowest value currently checked, it will spit out the lowest value in the list. This also means it will spit out the lowest distance, or closest humanoid.
I think this script is how to find the closest player and how much distance a player is to that part, sort of like a compass in minecraft in pvp game modes