I’d like to fix my NPC that follows the player using pathfinding.
Right now, if I move, it kind of glitches and snaps to a different rotation. If I keep circling around it, it eventually stops. If I stay put, it moves to me regularly without any problems.
https://gyazo.com/f763f838be8fc4e56af6c47eac362d15
local PathfindingService = game:GetService("PathfindingService")
local Char = script.Parent
local Hum = Char:FindFirstChildOfClass("Humanoid")
local Root = Char:FindFirstChild("HumanoidRootPart")
local Waypoints
local CurrentWaypoint
local Path
local Agroed
local CanMove = true
local Distance
local function CalculateJump(Waypoint)
if Waypoint.Action == Enum.PathWaypointAction.Jump then
Hum:ChangeState(Enum.HumanoidStateType.Jumping)
end
end
local function MoveTo()
if Waypoints then
CalculateJump(Waypoints[CurrentWaypoint])
Hum:MoveTo(Waypoints[CurrentWaypoint].Position)
CanMove = false
repeat
if Waypoints then
Distance = (Waypoints[CurrentWaypoint].Position - Root.Position).magnitude
end
wait()
until
Distance <= 5
end
end
local function OnWaypointReached(reached)
if Waypoints and reached == true and CurrentWaypoint < #Waypoints then
CurrentWaypoint = CurrentWaypoint + 1
MoveTo()
end
end
local function CreatePath(target)
if Path then
Path = nil
Waypoints = nil
CurrentWaypoint = nil
end
Path = PathfindingService:CreatePath()
Path:ComputeAsync(Root.Position, target.Position)
Waypoints = {}
if Path.Status == Enum.PathStatus.Success then
Waypoints = Path:GetWaypoints()
CurrentWaypoint = 1
MoveTo()
else
Hum:MoveTo(Root.Position)
end
Hum.MoveToFinished:Connect(OnWaypointReached)
end
local function LoopPlayers()
for i, v in pairs(game.Players:GetChildren()) do
local Char = v.Character or v.CharacterAdded:Wait()
if Char then
local PlrRoot = Char:WaitForChild("HumanoidRootPart")
CreatePath(PlrRoot)
Agroed = PlrRoot
end
end
end
wait(10)
LoopPlayers()
spawn(function()
while Agroed do
wait(.1)
if CanMove == false then
Hum.MoveToFinished:Wait()
end
CreatePath(Agroed)
end
end)
Anyone know why?