Hello everyone! I’ve been trying to make an NPC that chases a player using PathfindingService
, however over some time, the NPC bugs more and more. By bugging, I mean the NPC stops for a split second at each waypoint before continuing, instead of smoothly passing by each waypoint.
Here is a video of what I mean:
I am wondering if there was a way to stop this “buggy” movement so it can move smoothly all the time.
Here is the code for the NPC:
local PathfindingService = game:GetService("PathfindingService")
local ClosestDistance = 0
local HumanoidRootPartPosition
local Target
function GetNearest()
for i,v in pairs(workspace:GetChildren()) do
if game.Players:GetPlayerFromCharacter(v) then
if v:FindFirstChild("player") then
if not Target then
Target = game.Players:GetPlayerFromCharacter(v)
ClosestDistance = (v.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
HumanoidRootPartPosition = v.HumanoidRootPart.Position
else
local Magnitude = (v.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
if Magnitude < ClosestDistance and game.Players:GetPlayerFromCharacter(v) ~= Target then
Target = game.Players:GetPlayerFromCharacter(v)
ClosestDistance = (v.HumanoidRootPart.Position - script.Parent.HumanoidRootPart.Position).Magnitude
HumanoidRootPartPosition = v.HumanoidRootPart.Position
end
end
if HumanoidRootPartPosition then
HumanoidRootPartPosition = Vector3.new(math.floor(HumanoidRootPartPosition.X),math.floor(HumanoidRootPartPosition.Y),math.floor(HumanoidRootPartPosition.Z))
end
end
end
end
end
while wait() do
if Target then
local Path = PathfindingService:CreatePath()
Path:ComputeAsync(script.Parent.HumanoidRootPart.Position,Target.Character.HumanoidRootPart.Position)
local Waypoints = Path:GetWaypoints()
if Path.Status == Enum.PathStatus.Success then
local OldPosition = HumanoidRootPartPosition
for i,Point in pairs(Waypoints) do
script.Parent.Humanoid:MoveTo(Point.Position)
if Point.Action == Enum.PathWaypointAction.Jump then
script.Parent.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
local timeout = script.Parent.Humanoid.MoveToFinished:Wait(0.5)
if not timeout then
script.Parent.Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
break
end
if i % 3 == 0 then
HumanoidRootPartPosition = Target.Character.HumanoidRootPart.Position
HumanoidRootPartPosition = Vector3.new(math.floor(HumanoidRootPartPosition.X),math.floor(HumanoidRootPartPosition.Y),math.floor(HumanoidRootPartPosition.Z))
if HumanoidRootPartPosition ~= OldPosition then
break
end
OldPosition = HumanoidRootPartPosition
end
end
else
script.Parent.Humanoid:MoveTo(Target.Character.HumanoidRootPart.Position)
end
end
GetNearest()
end
Thank you for reading! Hope you can help.