I have a script always makes a gun fire at a dummy, but how would I make the gun to fire at the nearest dummy (eventually a player). I think I can set a variable to the distance of every player, but I don't know how to program for the script to pick the smallest one. Any help?
How would I get the nearest player?
1 answer
Hello, To my knowledge, the easiest way to do this would be to iterate between all players in the game and their characters. Here's an example:
local plrs = game:GetService("Players")
function getClosestPlayer(location) -- Function to get the information. Location is the location to find the closest player from.
local closestDistance = math.huge -- The closest player distance. This should start at a super big value to make sure all players are under that range, hence I use math.huge (infinity).
local closestCharacter = nil -- Track the closest character
for i, player in pairs(plrs:GetPlayers()) do -- Iterate over all players in the game.
if player.Character then -- Make sure the player has a character.
local distance = (player.Character-location).magnitude -- Find the distance between the two points. An easier way to calculate the distance formula.
if distance < closestDistance then -- Is the distance between these two less than the closest distance so far?
closestDIstance = distance -- Yes! Now set the closestDistance to this distance.
closestCharacter = player.Character -- Set the closestCharacter to the player's character.
end
end
end
return closestCharacter, closestDistance
end
-- Example of how to use the function:
local character, distance = getClosestPlayer(Vector3.new(0,0,0) -- Get the closest player to 0,0,0
print(character,distance)
Hope this helps (and hope there aren't any errors, lol).
- Eqic
3 comments
That looks super huge but it's mostly comments.
I've been playing around with this for a while now, hence the late response, and I'm not having much luck. How would I change this to test on a dummy, for example. Because I can't really test to see whats really going on when it is intended for players.
Well, you'd have to have a folder of all your dummies or some way to access them, and then instead of getting all the players in the game & their characters, you can get all of the dummies in a folder.
This discussion is preserved as it was. New answers, comments, and votes are closed.

2 comments
Do you want it to be always following a player?
Magnitude?