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

How can I get the closest character to the player?

Asked by
Psudar 882 Moderation Voter
4 years ago
Edited 4 years ago

I've been messing around with this script for a bit, until I finally realized I can't use table.sort() on a table of objects (the characters). So after that revelation, I realized I needed a way to return the character and also sort a table to get the smallest distance with the first index.

Any ideas? I'm stumped.

local function GetClosestCharacter()
    local distTable = {}
    for i, plr in pairs (Players:GetPlayers()) do
        if plr ~= Player then
            if Functions.IsTeamMate(plr, Player) then 
                if plr.Character and Character then 
                    local distance = (plr.Character.HumanoidRootPart.Position - Character.HumanoidRootPart.Position).Magnitude
                    if distance <= Configuration.HealMaxDistance.Value then  
                        table.insert(distTable, i, plr.Character) 
                    end
                end
            end
        end
    end
    table.sort(distTable)
    return distTable[1]
end

Heres what I had so far, which obviously trying to compare objects is syntactically incorrect, I just cant think of a way to return the character with the shortest distance to the player.

0
lol i promise that indentation isnt my fault; rip text editor on SH, needs a larger window lul Psudar 882 — 4y

1 answer

Log in to vote
2
Answered by 4 years ago
Edited 4 years ago

well, you can have two variables at the top of the function that both represent the ClosestCharacter and the ClosestDistance.

--just a proof of concept
local distTable = {0,1,1,2,3,5,8}
local ClosestDist,ClosestChar = math.huge

for i,dist in distTable do
    if dist<ClosestDist then
        ClosestChar = i
    end
end
print(ClosestDist,ClosestChar) --0, 1

This, applied in your example, could be similar to:

local function GetClosestCharacter()
    local closestDist,closestChar = math.huge
    for i, plr in pairs (Players:GetPlayers()) do
        if plr ~= Player then
            if Functions.IsTeamMate(plr, Player) then 
                if plr.Character and Character then 
                    local hrp = plr.Character.HumanoidRootPart
                    local hrp2 = Character.HumanoidRootPart
                    local distance = (hrp.Position - hrp2.Position).Magnitude
                    if distance <= Configuration.HealMaxDistance.Value then  
                        if distance < closestDist then
                            closestDist,closestChar =distance,plr.Character
                        end
                    end
                end
            end
        end
    end
    return closestChar
end
Ad

Answer this question