--!strict -- Good practice for writing better Luau code
-- 1. Get Necessary Services
local PathfindingService = game:GetService("PathfindingService")
local ReplicatedStorage = game:GetService("ReplicatedStorage") -- Needed for visual debugging
-- 2. Define NPC and Components
local npc = script.Parent -- Assumes the script is directly inside the NPC model
local humanoid = npc:FindFirstChild("Humanoid")
local primaryPart = npc.PrimaryPart -- Assumes PrimaryPart is set in the model properties
if not humanoid or not primaryPart then
warn("Noobster model is missing Humanoid or PrimaryPart!")
script:Destroy() -- Stop the script if essential components are missing
return
end
-- 3. Define the Target
-- You can get a part from the workspace:
local targetPart = workspace:FindFirstChild("TargetPart")
if not targetPart then
warn("No TargetPart found in Workspace! Create a part named 'TargetPart'.")
-- If no target part, the script will just wait or you could define a default position
-- For this example, we'll stop execution if no target is found
script:Destroy()
return
end
local targetPosition = targetPart.Position -- Get the position of the target part
-- Or define a hardcoded Vector3 position:
-- local targetPosition = Vector3.new(10, 5, 20) -- Example coordinates
-- 4. Create a Path Object
local pathParameters = {
-- Optionally customize pathfinding behavior here
-- AgentRadius, AgentHeight, AgentCanJump, AgentCanClimb, AgentCanDrop
-- You can also define AreaCosts for different terrain types
-- For a basic humanoid, defaults are usually fine:
AgentRadius = 2, -- Standard humanoid radius
AgentHeight = 5, -- Standard humanoid height
AgentCanJump = true,
AgentCanClimb = false, -- Set to true if your NPC can climb ladders/ropes
AgentCanDrop = true -- Set to true if your NPC can drop off ledges
}
local path = PathfindingService:CreatePath(pathParameters)
-- 5. Function to Compute and Follow Path
local function followPath(destination)
print("Noobster is computing path to:", destination)
-- Compute the path from the NPC's current position to the destination
-- Use the PrimaryPart's position as the start
local success, errorMessage = pcall(function()
path:ComputeAsync(primaryPart.Position, destination)
end)
if not success then
warn("Path computation failed:", errorMessage)
return -- Exit the function if computation failed
end
-- Check if the path is valid
local status = path.Status
if status ~= Enum.PathStatus.Success then
warn("Path computation failed with status:", status.Name)
-- You might try computing again or finding a new target here
return
end
-- Get the waypoints along the path
local waypoints = path:GetWaypoints()
print("Path computed successfully with", #waypoints, "waypoints.")
-- --- Optional: Visual Debugging ---
-- This helps you see the calculated path in the workspace.
-- You can disable this part once your pathfinding is working.
local debugPartsFolder = workspace:FindFirstChild("NoobsterDebug")
if debugPartsFolder then debugPartsFolder:Destroy() end -- Clean up previous path visuals
debugPartsFolder = Instance.new("Folder")
debugPartsFolder.Name = "NoobsterDebug"
debugPartsFolder.Parent = workspace
local lastPos = primaryPart.Position
for i, waypoint in ipairs(waypoints) do
-- Draw a small sphere at each waypoint
local waypointSphere = Instance.new("Part")
waypointSphere.Shape = Enum.PartShape.Sphere
waypointSphere.Material = Enum.Material.Neon
waypointSphere.Size = Vector3.new(1, 1, 1)
waypointSphere.Position = waypoint.Position
waypointSphere.Anchored = true
waypointSphere.CanCollide = false
waypointSphere.Color = Color3.new(0, 1, 0) -- Green
-- Make the last waypoint red
if i == #waypoints then
waypointSphere.Color = Color3.new(1, 0, 0) -- Red
end
waypointSphere.Parent = debugPartsFolder
-- Draw a line segment between waypoints (optional but useful)
local linePart = Instance.new("Part")
linePart.Material = Enum.Material.Neon
linePart.Color = Color3.new(0, 1, 1) -- Cyan
linePart.Anchored = true
linePart.CanCollide = false
linePart.Size = Vector3.new(0.2, 0.2, (waypoint.Position - lastPos).Magnitude)
linePart.CFrame = CFrame.lookAt(lastPos, waypoint.Position) * CFrame.new(0, 0, -linePart.Size.Z / 2)
linePart.Parent = debugPartsFolder
lastPos = waypoint.Position
end
-- --- End Optional: Visual Debugging ---
-- Move the NPC along the path
for i, waypoint in ipairs(waypoints) do
-- Check if the waypoint requires a jump action (if AgentCanJump is true)
if waypoint.Action == Enum.PathWaypointAction.Jump then
humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
-- Move the humanoid to the waypoint position
humanoid:MoveTo(waypoint.Position)
-- Wait until the humanoid reaches the waypoint or the MoveTo expires
-- humanoid.MoveToFinished:Wait(timeoutInSeconds) -- You can add a timeout if needed
local success, err = pcall(function()
humanoid.MoveToFinished:Wait()
end)
-- Check if the NPC is still alive and the loop should continue
if not humanoid.Parent then -- Check if humanoid object is still in game
warn("Noobster was removed during pathfollowing.")
break -- Exit the loop if NPC is gone
end
-- Optional: Check distance to waypoint. If too far after MoveToFinished, maybe recalculate?
-- This is basic, MoveToFinished:Wait() usually handles most cases.
local distanceToWaypoint = (primaryPart.Position - waypoint.Position).Magnitude
-- print("Reached waypoint", i, ". Distance remaining:", distanceToWaypoint) -- Useful for debugging
-- If the MoveTo failed or took too long (and we didn't reach the waypoint),
-- you might want to break the loop or recompute the path.
-- For this simple example, we'll just continue to the next waypoint.
end
print("Noobster reached the end of the path.")
end
-- 6. Start the pathfinding process
-- Call the function to make Noobster follow the path to the target position
followPath(targetPosition)
-- You could wrap this in a loop or connect it to an event (like a player entering a zone)
-- while task.wait(5) do -- Example: Recompute path every 5 seconds
-- if targetPart and targetPart.Parent then -- Ensure target still exists
-- followPath(targetPart.Position)
-- else
-- warn("TargetPart is gone. Stopping pathfinding.")
-- break
-- end
-- end
-- If you want to pathfind *once* and stop, the initial call is enough.