.
Posted in Tutorials
October 6, 2014 at 1:56 AM
Have NPC’s walk around your game!
By MrAtomikBlaster
Basic Lua knowledge required to understand this Tutorial.
Introduction
Have you ever wanted to put NPC’s in your game that can walk around? You may have known about this, through the use of Positions and Humanoids, but unfortunately, your NPC’s will often walk into walls and other objects blocking its path. But there’s a solution to that! The PathfiningService API!
How to use Pathfinding
Now, this is a bit more complicated than just using the MoveTo method on a Humanoid. However, this service does require that to use it to its fullest extent. You will of course still need the Vector3 values. This would be a bit too difficult to explain, so here’s a sample script already with notes:
local pathService = game:GetService("PathfindingService") local target = workspace.Target --The walk-to brick local torso = workspace.Figure.Torso --The NPC's torso --This will just create the path and make "Figure" walk along it-- --The arguments in order are: start, finish, maxDistance-- local path = pathService:CreateRawPathAsync(torso.Position, target.Position, 500) --Check if the path was successfully created-- if path.Status == Enum.PathStatus.FailStartNotEmpty then print("Path creation failure...") elseif path.Status == Enum.PathStatus.FailFinishNotEmpty then print("Path creation failure...") else local points = path:GetPointCoordinates() --Have Figure walk along the path-- local distance for i, point in pairs(points) do workspace.Figure.Humanoid:MoveTo(point) repeat distance = (point - torso.Position).magnitude wait() until distance < 3 --Love. end end
Restrictions
- You cannot set the maximum path distance above 500 magnitude.
- Bricks must be a certain height in order for the path to go around that brick.
- Sometimes, a path will be faulted and have the NPC run into the corner of a wall they’re trying to make a U-turn around. This is likely a glitch.
Not enough for you? Check out the official Wiki entry of Pathfinding.