I have this script that finds all the players in game and sends blocks created earlier in the script (x) after the player, so far everything works but only goes after one specific player, it doesn't go after the nearest, the target could be incredibly far away but would still only go after that one player as long as they're in range (range was changed for testing purposes)
spawn(function() local part = x for _, v in next, workspace:GetChildren() do if v:FindFirstChild("HumanoidRootPart") ~= nil and v:FindFirstChild("Humanoid") ~= pchar.Humanoid then local range = 25000 if (v.HumanoidRootPart.Position - x.Position).magnitude < range then found = true x.Anchored = false for i = 1, 40, 0.01 do bv.Velocity = (v.HumanoidRootPart.Position - part.Position).unit * 30 part.CFrame = CFrame.new(part.Position, v.HumanoidRootPart.Position) * CFrame.Angles(0, 80, 0) wait(0.02) end end end end end)
can someone help me make it find the nearest player? i can't really find out so i need help lol
You are now looping over all players and doing some code whenever someone is in range. Just move the variable range outside the loop and lower it whenever u find something closer, and remember which character had that range until u find a closer one. Then execute your code for the one who is closest.
also nil returns false, and anything else but false returns true. so if v:FindFirstChild("HumanoidRootPart") ~= nil can be shortened to if v:FindFirstChild("HumanoidRootPart")
I think you will be much more efficient and correct if you use the RegionFinder function to build a region from your particular desired location to some reasonable estimate. Then you can search for players within this region, compute distances between your selected location to each other player in the region itself and sort to find the nearest. If this estimated region fails to return anything, then you can choose to search the entire workspace or to take some other action.
The difference from your approach is that you don't have to loop through the entire workspace but instead through a very small but carefully-created subset (region) of it. Working with a subset will promise you good performance with a very large amount of players and objects in the workspace that are located very far away but at the same time also with few located- a loop with few iterations.