Whats the best way to make a npc follower?
Im trying to make an npc that will just walk behind the player and follow them around. I tried using pathfinding to do this but it seems to be really janky and chopy. Heres the code for it :
02 | local PathFindingService = game:GetService( "PathfindingService" ) |
05 | local targetCharacter = script.Parent.Parent.Parent |
06 | local target = targetCharacter:WaitForChild( "HumanoidRootPart" ) |
07 | local localCharacter = script.Parent.Parent |
08 | local localHumanoid = localCharacter:WaitForChild( "Humanoid" ) |
09 | local localRoot = localCharacter:WaitForChild( "HumanoidRootPart" ) |
13 | print ( "Moving to player" ) |
14 | local pos = target.Position + target.CFrame.LookVector * - 2 + target.CFrame.RightVector * 2 |
15 | localHumanoid:MoveTo(pos) |
18 | function drawWaypoint(point) |
19 | local part = Instance.new( "Part" , workspace) |
20 | part.BrickColor = BrickColor.new( "White" ) |
22 | part.Material = "Neon" |
23 | part.Transparency = 0.25 |
26 | part.CanCollide = false |
27 | part.Size = Vector 3. new( 1 , 1 , 1 ) |
28 | part.Position = point.Position |
29 | game:GetService( "Debris" ):AddItem(part, 1 ) |
32 | function generatePath() |
33 | print ( "Generating Path" ) |
34 | local path = PathFindingService:CreatePath() |
35 | path:ComputeAsync(localRoot.Position ,target.Position + target.CFrame.LookVector * - 2 + target.CFrame.RightVector * 2 ) |
39 | function moveAlongWaypoints(path) |
40 | print ( "Moving along waypoints" ) |
41 | local wayPoints = path:GetWaypoints() |
42 | for _,waypoint in pairs (wayPoints) do |
43 | print ( "Next waypoint" ) |
44 | drawWaypoint(waypoint) |
45 | localHumanoid:MoveTo(waypoint.Position) |
46 | localHumanoid.MoveToFinished:Wait() |
51 | local path = generatePath() |
52 | if path ~ = nil and path.Status = = Enum.PathStatus.Success then |
53 | print ( "Path was Successfully made" ) |
54 | moveAlongWaypoints(path) |
56 | warn( "Failed to generate path" ) |
64 | game:GetService( "RunService" ).Stepped:Wait() |
If some one could fix the code to make the movement smoother or just tell me a better way I would apreaciate it alot :)
https://gyazo.com/3e0e075f6b6d6f740ba2e5d302e55b8a