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

How do i make sure the NPC hunts down the closest Humanoid?

Asked by 3 years ago

My current script lets the NPC hunt the player who joined last, the NPC doesnt change target until that person leaves. I need to script it so that the NPC hunts the player who is closest, i tried to work it out myself with IntValues. Please someone help me!

function getHumanoid(model)
    for _, v in pairs(model:GetChildren()) do
        if v:IsA'Humanoid' then
            return v
        end
    end
end


local ai = script.Parent
local human = getHumanoid(ai)
local hroot = ai.HumanoidRootPart
local zspeed = hroot.Velocity.magnitude


local pfs = game:GetService("PathfindingService")

function GetPlayerNames()
    local players = game:GetService('Players'):GetChildren()
    local name = nil
    for _, v in pairs(players) do
        if v:IsA'Player' then
            name = tostring(v.Name)
        end
    end
    return name
end

spawn(function()
    while wait() do
        print()
    end
end)

function GetPlayersBodyParts(t)
    local torso = t
    if torso then
        local figure = torso.Parent
        for _, v in pairs(figure:GetChildren()) do
            if v:IsA'Part' then
                return v.Name
            end
        end
    else
        return "HumanoidRootPart"
    end
end

function GetTorso(part)
    local chars = game.Workspace:GetChildren()
    local torso = nil
    for _, v in pairs(chars) do
        if v:IsA'Model' and v ~= script.Parent and v.Name == GetPlayerNames() then
            local charRoot = v:FindFirstChild'HumanoidRootPart'
            if (charRoot.Position - part).magnitude < SearchDistance then
                torso = charRoot
            end
        end
    end
    return torso
end

Answer this question