Hello, so I’m making a pathfinding npc. The issue is that when it’s meant to switch paths it’ll twitch as you can see here
This is my code:
local function Move()
Called = true
local Target = GetTarget()
if Target then
local PrimePart = Target.PrimaryPart
if PrimePart then
local Path = PFS:CreatePath()
Path:ComputeAsync(Torso.Position,PrimePart.Position)
if Path.Status == Enum.PathStatus.Success then
local Waypoints = Path:GetWaypoints()
Called = false
for i,v in pairs(Waypoints) do
if Called == false then
if v.Action == Enum.PathWaypointAction.Jump then
Humanoid.Jump = true
end
Humanoid:MoveTo(v.Position)
Humanoid.MoveToFinished:Wait()
else
break
end
end
end
end
end
end
RunService.Stepped:Connect(Move)
can someone explain to me why this is happening and how I can fix it? Any help is appreciated!
You binded the move function to RunService.Stepped which will make the npc repathfind and try to go to the first waypoint of the new function. Your Called variable shouldn’t work because the new function is starting a new :MoveTo() while the old one isn’t cancelled because it is waiting for Humanoid.MoveToFinished:Wait(), causing the going back and forth thing.
So you want to update the waypoints every frame, but only move to the next waypoint. Something like this where you calculate waypoints every frame and only move to the next one.
local PFS = game:GetService("PathfindingService")
local torso = game.Workspace.Dummy.Torso
local hum = game.Workspace.Dummy.Humanoid
game:GetService("RunService").Stepped:Connect(function()
local target = game.Workspace.Part
local path = PFS:CreatePath()
path:ComputeAsync(torso.Position, target.Position)
local waypoints = path:GetWaypoints()
if waypoints and waypoints[2] then
local data = waypoints[2]
if data.Action == Enum.PathWaypointAction.Jump then
hum.Jump = true
end
hum:MoveTo(data.Position)
end
end)
if waypoints and waypoints[2] then
local data = waypoints[2]
hum:MoveTo(data.Position)
end
Some how this single string of code managed to completely fix the twitching and inconsistency of my pathfinding script while allowing npcs to pathfind around objects. THANK YOU!