I’ve taken to looking at PathfindingService again and I’ve decided to develop my own following NPC. My aim was to make it search for the closest player and then move to it. However I’ve ran into a bit of an issue. I want the script to constantly check and move to the closest player and I can’t think of a good way to implement this. I’ve taken to just calling the function repeatedly with a while wait() loop but doing this only makes movement jittery. Any help making this script run wel would be appreciated.
Code:
local PathfindingService = game:GetService("PathfindingService")
local Humanoid = script.Parent.Humanoid
local HumanoidRootPart = script.Parent.HumanoidRootPart
local MaxDistance = 200
function FindClosestTarget(MaxDist, TableOfCurrentPlayers)
local Target
local SmallestDistance = MaxDist
local PlayerWithSmallerDistance
for _, player in pairs(TableOfCurrentPlayers) do
local distance = player:DistanceFromCharacter(HumanoidRootPart.Position)
if distance < SmallestDistance then
SmallestDistance = distance
PlayerWithSmallerDistance = player
end
end
Target = PlayerWithSmallerDistance
if Target ~= nil then --Check if it isn't nil
print(Target.Name)
end
return Target
end
function FindAndMoveToTargetPos()
local TargetToMoveTo = FindClosestTarget(MaxDistance, game.Players:GetPlayers())
local TargetChar = TargetToMoveTo.Character
if TargetChar then
local Target_HRP = TargetChar:WaitForChild("HumanoidRootPart",5)
local path = PathfindingService:CreatePath()
path:ComputeAsync(HumanoidRootPart.Position, Target_HRP.Position)
local waypoint = path:GetWaypoints()
for i, waypoint in pairs(waypoint) do
if waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid.ChangeState(Enum.HumanoidStateType.Jumping)
end
Humanoid:MoveTo(waypoint.Position)
Humanoid.MoveToFinished:Wait()
end
end
return TargetToMoveTo
end
while wait() do
local Closest = FindClosestTarget(MaxDistance,game.Players:GetPlayers())
local CurrentTarget = FindAndMoveToTargetPos()
if Closest ~= CurrentTarget then
FindAndMoveToTargetPos()
end
end
Please tell me if I’ve formatted this wrong or something, this is my first topic.
P.S. If you want to test it and see for yourself my issue, just put the script in an unanchored R15 NPC.