Make NPC follow/chase players

0

Make an NPC [with Humanoid inside] named Giraffe patrol chase the closest player

Workspace/Script
local DELAY = 2

local giraffe  = game.Workspace.Giraffe
local humanoid = giraffe.Humanoid
local npcHRP   = giraffe.HumanoidRootPart

local function GetNearestPlayer(minimumDistance)
    local closestMagnitude = minimumDistance or math.huge
    --minimumDistance is a number in studs
    local closestPlayer
    for i,v in next, game.Players:GetPlayers() do
        local Character = v.Character
        if (Character) then
            local humanoid = Character.Humanoid
            local HRP = Character.HumanoidRootPart
            if (humanoid.Health > 0) then
                local mag = (npcHRP.Position - HRP.Position).Magnitude
                if (mag <= closestMagnitude) then
                    closestPlayer = v
                    closestMagnitude = mag
                end
            end
        end
    end
    return closestPlayer
end

local nearestPlayer = nil 
while wait(DELAY) do
    nearestPlayer = GetNearestPlayer()
    if nearestPlayer then
        humanoid:MoveTo(nearestPlayer.Character.HumanoidRootPart.Position)
        humanoid.MoveToFinished:Wait()
    end
end

  • 0 posts
  • 1 subtopic
  • 8 months ago by vince