“How to Make a Pathfinding NPC in Roblox! Pathfinding Tutorial Part 4”

Опубликовано: 28 Июль 2026
на канале: Codewrks
93
4

Learn how to make your NPC move smarter, avoid obstacles, and react more naturally using Roblox Lua scripting and PathfindingService.

Server Script (Place in the NPC): Place a walking animation inside the script.
task.wait(5)

local Workspace = game:GetService("Workspace")
local PathfindingService = game:GetService("PathfindingService")

local npc2 = script.Parent
local humanoid = npc2:WaitForChild("Humanoid")
local rootPart = npc2:WaitForChild("HumanoidRootPart")
local animator = humanoid:WaitForChild("Animator")

-- Walking animation
local animation = script:WaitForChild("Animation")
local animationTrack = animator:LoadAnimation(animation)
animationTrack:AdjustSpeed(0.2)
animationTrack:Play()

-- Target parts
local findPart = Workspace:WaitForChild("FindPart")
local secondPart = Workspace:WaitForChild("SecondPart")
local thirdPart = Workspace:WaitForChild("ThirdPart")
local fourthPart = Workspace:WaitForChild("FourthPart")

-- Function to follow path
local function followPath(destination)
local path = PathfindingService:CreatePath({
AgentRadius = 3,
AgentHeight = 6,
AgentCanJump = true,
AgentJumpHeight = 12, -- adjust for your gap heights
AgentCanClimb = true,
AgentMaxSlope = 45,
})

local success, errorMessage = pcall(function()
path:ComputeAsync(rootPart.Position, destination)
end)

if success and path.Status == Enum.PathStatus.Success then
local waypoints = path:GetWaypoints()
for _, waypoint in ipairs(waypoints) do
humanoid:MoveTo(waypoint.Position)

if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid.Jump = true
end

-- Wait until NPC reaches waypoint before moving to next
local reached = humanoid.MoveToFinished:Wait()
if not reached then
warn("NPC failed to reach waypoint at "..tostring(waypoint.Position))
end
end
else
warn("Path failed: " .. (errorMessage or "Unknown"))
end
end

-- Function to handle NPC movement sequence with pauses
local function moveSequence()
local targets = {findPart, secondPart, thirdPart, fourthPart}

for index, target in ipairs(targets) do
-- Pause animation before moving
animationTrack:Stop()
task.wait(1)
animationTrack:Play()

-- Move to target
followPath(target.Position)
end

-- Final stop
animationTrack:Stop()
print("NPC reached the final destination!")
end

-- Start NPC movement
moveSequence()