I'm currently working on making my own pathfinding enemy script and so far everything has worked. However the NPC's movement is jittery and it seems to stop and move very often. I feel this is to do with my loop calling the function every .03 seconds. All I'd like is it to not do this, but for it to be able to seamlessly switch between targets and for it not to act so jittery. Help 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
