Hello!
I need help figuring out how I can make this script so it makes the NPC always walk to the nearest player even if they move, and if they do move then it should find the new nearest or recalculate the path the second they move. Help would be appreciated, here is my script, when I tried to do a loop, it just said HumanoidRootPart couldn’t be found.
local PathfindingService = game:GetService("PathfindingService")
local runService = game:GetService("RunService")
local human = script.Parent:WaitForChild("Humanoid")
local torso = script.Parent:WaitForChild("Torso")
local magnitude = math.huge
local closestvector = 0
local function returner()
for i,v in pairs(game.Players:GetPlayers()) do
if magnitude > (v.Character.HumanoidRootPart.Position - torso.Position).Magnitude and (v.Character.HumanoidRootPart.Position - torso.Position).Magnitude <= 50 then
magnitude = (v.Character.HumanoidRootPart.Position - torso.Position).Magnitude
closestvector = v.Character.HumanoidRootPart.Position
end
end
return closestvector
end
local closestvector = returner()
runService.Heartbeat:Connect(function()
local path = PathfindingService:CreatePath()
path:ComputeAsync(torso.Position, Vector3.new(closestvector))
local waypoints = path:GetWaypoints()
for i, waypoint in pairs(waypoints) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
human:ChangeState(Enum.HumanoidStateType.Jumping)
end
human:MoveTo(waypoint.Position)
human.MoveToFinished:Wait()
end
closestvector = returner()
human:MoveTo(Vector3.new(closestvector))
end)