Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I get the nearest player?

Asked by 6 years ago

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?

0
Do you want it to be always following a player? magicguy78942 238 — 6y
0
Magnitude? greatneil80 2647 — 6y

1 answer

Log in to vote
0
Answered by
Eqicness 255 Moderation Voter
6 years ago

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
0
That looks super huge but it's mostly comments. Eqicness 255 — 6y
0
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. tygerupercut3 68 — 6y
0
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. Eqicness 255 — 6y
Ad

Answer this question