Enemy FSM AI: Idle, Patrol, Alert, and Combat
Generate a robust enemy AI for Roblox using a finite state machine (FSM) with the idle, patrol, alert, and combat states. The result is designed for NPCs with Humanoid, waypoint-based movement, player detection by distance, field of view, and line-of-sight raycasting.
The prompt instructs the AI to adapt the code to the real context of your project, including names of models, parts, folders, attributes, RemoteEvents, and existing damage systems. It requires a secure server-side implementation, with PathfindingService, invalid target handling, prevention of excessive route recalculation, and practical testing instructions in Roblox Studio.
Ideal for developers who want a professional, expandable foundation for guard enemies, monsters, soldiers, or bosses, without delegating critical combat or damage decisions to the client.
Act as a senior Roblox Luau developer, specialized in server-authoritative NPC AI, finite state machines (FSM), `PathfindingService`, and secure architecture for multiplayer games. Generate a complete, ready-to-use implementation of an enemy AI with the `Idle`, `Patrulha`, `Alerta`, and `Combate` states, rigorously adapting the result to the context of my game provided below. Before writing the code, analyze the context I will paste at the end of this message. It may contain exact names of objects in the Explorer, the enemy model structure, names of Parts, waypoint folders, Attributes, CollectionService tags, existing modules, RemoteEvents/RemoteFunctions, and my current damage system. Use these names literally when they are provided. If any essential information is missing, do not invent a complex integration: state the assumptions adopted at the beginning of the result and use configurable names concentrated in a `CONFIG` section at the top of the script. If the context is empty, assume a standard structure that is clearly documented. The main deliverable must be exactly one server `Script`, placed inside the `Model` of each enemy in Workspace (for example: `Workspace.Enemies.NomeDoInimigo.AIController`). Explain that the Model needs to contain `Humanoid` and `HumanoidRootPart`, and that the AI's movement and decisions occur exclusively on the server. If I provide a centralized NPC architecture or an existing ModuleScript, adapt the location and interface without turning the solution into multiple files, unless I explicitly ask for that. Implement an explicit FSM, preferably with a state table, transition function, and controlled cleanup when changing states. The minimum behaviors are: - `Idle`: enemy standing still or waiting for a configurable time; periodically looks for valid players. - `Patrulha`: moves through a configurable folder of waypoints in order or in a controlled random manner; uses pathfinding when necessary; returns to idle if there are no waypoints. - `Alerta`: triggered when detecting or suspecting a player; stores the last known position, waits for a configurable period, and investigates that position before giving up. - `Combate`: chases the target while it remains valid and visible/identified; respects minimum attack distance, cooldown, and range. The attack must be an isolated and safe function, prepared for integration with my damage system. Detection must consider maximum distance, field of view based on the enemy's `LookVector`, and raycast for line of sight, with `RaycastParams` excluding the NPC's own model. Validate that the target is a real player, that the `Character`, `Humanoid`, `HumanoidRootPart`, and health are valid, and that the target has not been destroyed. Keep memory of the last seen position and a target-loss timer to avoid chaotic switching between states. Choose the most appropriate target, usually the nearest visible player, without running heavy loops every frame. Use `PathfindingService:CreatePath()` and route waypoints resiliently. Handle failed paths, `MoveToFinished`, stuck NPCs, changed destinations, obstacles, and limited recalculation attempts. Include configurable intervals for target scanning and path recalculation, avoiding creating too many paths. Do not use `while true do` without `task.wait()`, do not connect events repeatedly on every state change without disconnecting them, and clean up connections/tasks when the Humanoid dies or the Model is destroyed. Preserve the normal physics of the Humanoid and do not use nonexistent APIs or Lua syntax incompatible with Luau. Security is mandatory: the server must be authoritative for detection, movement, target selection, and damage. Never trust the client to report damage, health, currency, inventory, enemy position, or attack results. If my context includes RemoteEvents/RemoteFunctions, validate on the server for type, existence, distance, player state, rate limit, and permissions before any relevant effect. For the standard attack, apply damage only on the server through a well-commented `applyDamage` function; if there is a combat module provided by me, call its API only after server-side validations. Do not create unnecessary RemoteEvents. First provide a short section called `Premissas e instalação`, indicating the exact Script location and the expected structure in the Explorer. Then provide the full Luau code, with no pseudocode, no omitted excerpts, and no use of `...`, inside a single Markdown code block with the `lua` language. Comment the important parts in Portuguese, especially configurations, state transitions, vision/raycast, pathfinding, target validation, attack, and cleanup. The script must be ready to paste into Roblox Studio. After the code block, include an objective section `Como testar no Roblox Studio` with steps to create/configure the NPC, create waypoints, adjust attributes/configurations, use Test > Start with multiple players, and verify the four states. Also include a brief list of common problems and diagnostics, such as missing HumanoidRootPart, collision group preventing raycast, inaccessible waypoints, and Network Ownership. Do not ask follow-up questions: make reasonable decisions based on the context and document the assumptions. Below is the context of my game for you to use and respect: [COLE AQUI a estrutura do Explorer, nomes do Model/Humanoid/RootPart, pasta de waypoints, atributos, tags, módulos de combate, RemoteEvents existentes, regras de dano e qualquer requisito adicional.]