Intelligent NPC with Patrol, Pursuit, and Pathfinding
This prompt creates an advanced AI system for hostile NPCs in Roblox, structured as a state machine to reliably switch between patrol, pursuit, attack, and return-to-route behaviors. The result uses PathfindingService on the server, recalculates routes when needed, and handles obstacles, invalid targets, and path failures.
It is ideal for adventure games, survival, RPGs, tycoons with enemies, and multiplayer combat experiences. The prompt asks the model to adapt the code to the real hierarchy of your project, including NPC names, waypoints, attributes, animations, existing remote events, and damage rules.
The implementation prioritizes multiplayer safety: AI decisions, target validation, and damage application are handled exclusively by the server. In the end, you receive commented Luau code, ready to paste, plus clear instructions for installation and testing in Roblox Studio.
Act as a senior Roblox developer, specialized in Luau, NPC AI, and safe multiplayer architecture. Generate a complete server Script for an NPC with patrol, pursuit, and attack using PathfindingService, adapted to the context of my project provided below. Before writing the code, analyze the context and assume only what is explicitly defined. If any essential detail is missing, do not stop to ask questions: implement a clear configuration at the top of the script, with safe default values and comments indicating what I should adjust. Do not invent RemoteEvents, folders, or required objects without declaring where they should exist. The result must be usable in multiplayer and must work with multiple players simultaneously. ## Context of my game (I will fill this in before sending) - Name and path of the NPC Model in the Explorer: [EX.: Workspace.Enemies.Guard] - NPC parts: Humanoid = [name], HumanoidRootPart = [name], Animator/animations = [details or "does not exist yet"] - Folder/model of patrol waypoints and names of the Parts: [EX.: Workspace.Waypoints.GuardRoute] - The NPC should patrol in order, randomly, or back and forth: [mode] - Detection distance, loss distance, field of view, and attack distance: [values] - Damage, attack cooldown, and desired behavior: [values; contact, hitbox, or radius] - Should it use Attributes on the NPC? Provide existing names/values: [details] - Existing RemoteEvents/RemoteFunctions and their paths: [details; or "none needed"] - Extra rules: factions, ignored players, safe zones, teams, NPC targets, animations, sounds, loot, etc.: [details] ## Required delivery Create exactly **one Script** (not a LocalScript and not a ModuleScript), to be placed as a direct child of the **NPC Model in Workspace**. It must run entirely on the server. If configuration via Attributes is needed, the Script itself must read optional Attributes from the Model and use documented default values when they do not exist. Do not depend on client-side code for movement, decision-making, damage, state validation, or state control. Implement an explicit state machine, with at least the states `Patrol`, `Chase`, `Attack`, and `ReturnToPatrol` (or equally well-documented equivalents). The NPC must: 1. Find the nearest eligible player, validating `Player`, `Character`, `Humanoid`, `HumanoidRootPart`, health, and distance. 2. Detect targets by perception radius and, when configured, by field of view. Use `workspace:Raycast` with `RaycastParams` for line of sight, correctly ignoring the NPC itself. Do not treat walls as clear vision. 3. Patrol the waypoints robustly. Validate that the folder exists, filter only `BasePart`, sort by name when appropriate, and handle routes without waypoints without freezing the script. 4. Pursue using `PathfindingService:CreatePath()` and `ComputeAsync()`, with configurable agent parameters (radius, height, jump, and slope). Traverse waypoints using `Humanoid:MoveTo()` and `MoveToFinished` without blocking indefinitely. 5. Recompute the path with a controlled interval, only when the target moved significantly, the path was blocked, the NPC got stuck, or the route failed. Connect and disconnect `Path.Blocked` correctly to avoid connection leaks. 6. Attack only when the target is alive, within range, and respecting cooldown. Apply damage exclusively on the server with `Humanoid:TakeDamage()` or an equivalent safe mechanism. Never use a RemoteEvent for the client to report damage, coins, range, or a valid target. 7. Stop or update movement when entering attack range; resume pursuit when leaving range; lose the target after a configurable distance/time; and return to the appropriate waypoint after losing pursuit. 8. Handle NPC death/destruction, target character removal, respawn, and pathfinding errors without infinite loops, excessive `task.wait()`, or orphaned connections. Use current Luau best practices: `game:GetService`, local variables, `task.wait`, `os.clock` when useful, defensive validations, `pcall` only where it makes sense, and technical comments in Portuguese. Do not use deprecated APIs. Avoid per-frame logic in `RunService` if a loop with configurable frequency is sufficient. The code must be self-contained, readable, and efficient for multiple NPCs. Deliver the response in this order: first a brief list of prerequisites in the Explorer; then the full Luau code in a single markdown block started exactly with ```lua; then numbered instructions to install, configure the Attributes/waypoints, and test in Roblox Studio with at least two players using Test > Start Server. Do not omit any part of the code, do not use pseudocode, and do not leave functions marked as "implement later".