RobloxScripterAI
Discord ↗
Link Copied to Clipboard
×
"when the npc reaches waypoint 19, it is going back to waypoint 2 instead of going to waypoint 20"
-- server script local pfs = game:GetService("PathfindingService") local dummy = script.Parent local waypoints = script.Parent.Parent.Parent.Waypoints:GetChildren() -- List of waypoints local aggroRange = 10 -- define the aggro range local aggroedPlayers = {} -- table to hold players in aggro range local currentWaypointIndex = 1 -- Order waypoints by name (which should be numbers) table.sort(waypoints, function(a, b) return a.Name < b.Name end) -- Function to check for players in aggro range local function checkAggro() for _, player in pairs(game.Players:GetPlayers()) do if (player.Character.HumanoidRootPart.Position - dummy.HumanoidRootPart.Position).Magnitude < aggroRange then aggroedPlayers[player.Name] = player else aggroedPlayers[player.Name] = nil end end end -- Function to move to the next waypoint local function moveToNextWaypoint() while true do if currentWaypointIndex == 19 then currentWaypointIndex = 20 else currentWaypointIndex = (currentWaypointIndex % #waypoints) + 1 end print("Moving to waypoint: " .. waypoints[currentWaypointIndex].Name .. " at position: " .. tostring(waypoints[currentWaypointIndex].Position)) -- log the next waypoint local path = pfs:CreatePath() path:ComputeAsync(dummy.HumanoidRootPart.Position, waypoints[currentWaypointIndex].Position) for _, waypoint in pairs(path:GetWaypoints()) do dummy.Humanoid:MoveTo(waypoint.Position) dummy.Humanoid.MoveToFinished:Wait() end checkAggro() -- check for players in aggro range if next(aggroedPlayers) ~= nil then -- if the aggroedPlayers table is not empty, pursue the nearest player local nearestPlayer = nil local nearestDist = math.huge for _, player in pairs(aggroedPlayers) do local dist = (player.Character.HumanoidRootPart.Position - dummy.HumanoidRootPart.Position).Magnitude if dist < nearestDist then nearestDist = dist nearestPlayer = player end end if nearestPlayer then dummy.Humanoid:MoveTo(nearestPlayer.Character.HumanoidRootPart.Position) dummy.Humanoid.MoveToFinished:Wait() end end task.wait(1) end end -- Start the NPC's behavior spawn(moveToNextWaypoint)