_James

Pathfinding NPC for Tutorial

Feb 2nd, 2019
1,565
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.94 KB | None | 0 0
  1. local get_path = require( game.ServerScriptService:WaitForChild("A*") )
  2.  
  3. local fig = script.Parent
  4. local torso = fig.WaitForChild("HumanoidRootPart")
  5. local humanoid = fig.WaitForChild("Humanoid")
  6.  
  7. function follow_path(goal)
  8.     if not goal then return end
  9.    
  10.     local from = torso.Position
  11.     local to = goal.Position
  12.     local path = get_path(from, to)
  13.    
  14.     for _,node in ipairs(path or {})do
  15.         repeat wait()
  16.             humanoid:MoveTo(node)
  17.         until (node - torso.Position).Magnitude <= 4
  18.     end
  19. end
  20.  
  21.  
  22. function get_closest_player(to)
  23.     local dist = math.huge
  24.     local output = nil
  25.     for _,user in ipairs(game.Players:GetPlayers())do
  26.         local diff = user:DistanceFromCharacter(to)
  27.         if diff < dist and user.Character then
  28.             dist = diff
  29.             output = user.Character
  30.         end
  31.     end
  32.     return output
  33. end
  34.  
  35. while wait() do
  36.     local user = get_closest_player(torso.Position)
  37.     local root = user and user:FindFirstChild("HumanoidRootPart")
  38.     follow_path(root)
  39. end
Advertisement
Add Comment
Please, Sign In to add comment