A better method to path find to a moving player?
So I was attempting to create a path finding script for my NPC using ROBLOX's path finding service. The script is supposed to follow the player and not get stuck on walls and make sure it can follow them where ever they go.
The current script does function, its just after the player a NPC is following dies the NPC begins to track the next player but then will start going between the spot the first player died and the path in which the new player is on.
My current script
01 | local pathService = game:GetService( "PathfindingService" ) |
02 | local teams = game:GetService( "Teams" ) |
03 | local debris = game:GetService( "Debris" ) |
05 | local maxDistance = 512 |
07 | local undeadTeam = teams:FindFirstChild( "Undead" ) |
08 | local survivorsTeam = teams:FindFirstChild( "Survivors" ) |
10 | local upper = script.Parent.UpperTorso |
13 | local humanoid = script.Parent.Humanoid |
17 | local OldSpot = target.Character.UpperTorso.Position |
19 | local path = pathService:CreatePath() |
20 | path:ComputeAsync(upper.Position,OldSpot) |
21 | local waypoints = path:GetWaypoints() |
23 | for _, waypoint in pairs (waypoints) do |
24 | newSpot = target.Character.UpperTorso.Position |
25 | local part = Instance.new( "Part" ) |
26 | part.Size = Vector 3. new( 0.6 , 0.6 , 0.6 ) |
27 | part.Position = waypoint.Position |
29 | part.CanCollide = false |
30 | part.Parent = game.Workspace |
32 | debris:AddItem(part, 0.75 ) |
33 | humanoid:MoveTo(waypoint.Position) |
34 | humanoid.MoveToFinished:Wait() |
35 | if (newSpot-OldSpot).magnitude> 5 then |
42 | for i,v in pairs (game:GetService( "Players" ):GetChildren()) do |
43 | local shortestDistance = 512 |
44 | if v.Team = = survivorsTeam and workspace:FindFirstChild(v.Name) then |
45 | local chr = v.Character |
47 | if chr:FindFirstChild( "Humanoid" ).Health > 0 then |
48 | if (chr:FindFirstChild( "UpperTorso" ).Position-upper.Position).magnitude < shortestDistance then |
49 | shortestDistance = (chr:FindFirstChild( "UpperTorso" ).Position-upper.Position).magnitude |
61 | target.Team = = undeadTeam |
if you have any questions ask away I will try and reply to them as soon as possible.