Trying to make an NPC follow the closest player. I got the NPC to follow the player, but the problem is that the movement is not smooth and I don’t know why.
I’ve been searching for solutions on the dev forum, nothing helped so far though
Feel free to ask further questions, thanks.
wait(3)
local pfs = game:GetService("PathfindingService") -- Pathfinding service
local hum = script.Parent:WaitForChild("Humanoid") -- npc humanoid
local torso = script.Parent:WaitForChild("Torso") -- npc torso
local players = game:GetService("Players")
local distance
local closestPlayer, closestDistance = nil, math.huge
function checkPlayerDistance() -- Function will loop through the players and get the nearest player
local children = players:GetChildren()
for i,v in pairs(children) do
distance = (v.Character:FindFirstChild("HumanoidRootPart").Position - torso.Position).magnitude
if distance <= closestDistance then
closestDistance = distance
closestPlayer = v
end
end
return closestPlayer
end
while wait() do -- NPC will follow the nearest player
local returnedPlayer = checkPlayerDistance()
local path = pfs:CreatePath()
path:ComputeAsync(torso.Position, returnedPlayer.Character.HumanoidRootPart.Position)
local waypoints = path:GetWaypoints()
for i,waypoint in pairs(waypoints) do
hum:MoveTo(waypoint.Position)
hum.MoveToFinished:Wait()
if waypoint.Action == Enum.PathWaypointAction.Jump then
hum.Jump = true
end
end
closestDistance = math.huge
end
Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.