Advertisement
whileDo

AUTO MOVE TO NEAREST PLAYER SCRIPT ROBLOX

Sep 25th, 2024
374
-1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.98 KB | Gaming | 0 1
  1. local npc = game.Workspace.NPC -- change NPC to nickname
  2. local players = game.Players:GetPlayers()
  3.  
  4. local function findNearestPlayer()
  5.     local minDist = math.huge
  6.     local nearestPlayer = nil
  7.     for _, player in pairs(players) do
  8.         local dist = (npc.Position - player.Character.HumanoidRootPart.Position).magnitude
  9.         if dist < minDist then
  10.             minDist = dist
  11.             nearestPlayer = player
  12.         end
  13.     end
  14.     return nearestPlayer
  15. end
  16.  
  17. local function moveToNearestPlayer()
  18.     local nearestPlayer = findNearestPlayer()
  19.     if nearestPlayer then
  20.         local path = game:GetService("PathfindingService"):CreatePath({
  21.             AgentRadius = 2,
  22.             AgentHeight = 5,
  23.             AgentCanJump = true,
  24.             AgentJumpHeight = 10
  25.         })
  26.         path:ComputeAsync(npc.Position, nearestPlayer.Character.HumanoidRootPart.Position)
  27.         path:MoveTo(npc)
  28.     end
  29. end
  30.  
  31. while true do
  32.     moveToNearestPlayer()
  33.     wait(1)
  34. end
  35.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement