К основному содержанию
скилл CX Codex

roblox-npc-ai · el4cteo — скилл для Claude Code: ИИ для NPC

Скилл roblox-npc-ai для Claude Code помогает создавать ИИ врагов, питомцев и других NPC в Roblox. Используется для настройки поиска пути, преследования, атак и поведения персонажей, а также для исправления застревающих NPC.

MIT 1 200 установок ★ 131 обновлён 2026-11-03

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add EL4CTEO/roblox-skills --skill roblox-npc-ai -a claude-code
Открыть на GitHub

Что делает roblox-npc-ai

Скилл описывает серверную логику NPC и поиск пути через PathfindingService. В нём разобраны состояния ожидания, преследования, атаки и возвращения домой, проверка видимости цели, повторный расчёт пути и реакция на препятствия. Для движения без преград NPC может идти прямо к цели.

Для множества NPC предлагается общий цикл обновления вместо отдельного бесконечного цикла на каждого персонажа; также описаны создание объектов, их повторное использование и распределение нагрузки. Расстояние между начальной и конечной точкой пути ограничено 3 000 studs, а бюджет поиска — 20 000 узлами. Клиентский расчёт видит только загруженную геометрию, поэтому пути нужно строить на сервере.

Какие задачи решает

  • настроить поиск пути NPC по карте Roblox
  • заставить врага преследовать цель и атаковать её
  • вернуть NPC домой после выхода за пределы зоны
  • разобраться, почему NPC застревает или дёргается
  • организовать обновление поведения множества NPC

Примеры запросов агенту

  • Создай врага для Roblox, который ищет игрока, преследует его и атакует.
  • Настрой питомца-NPC, который следует за игроком и возвращается домой.
  • Разбери, почему NPC застревает на пути и нагружает сервер.

Как установить roblox-npc-ai

1Через Skills CLI (Vercel)

npx skills add EL4CTEO/roblox-skills --skill roblox-npc-ai -a claude-code

2Вручную: положить файлы

~/.claude/skills/roblox-npc-ai/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/roblox-npc-ai/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о roblox-npc-ai

Как установить roblox-npc-ai в Claude Code?

Выполни npx skills add EL4CTEO/roblox-skills --skill roblox-npc-ai -a claude-code. Файл скилла находится по пути ~/.claude/skills/roblox-npc-ai/SKILL.md.

Что делает roblox-npc-ai?

Скилл помогает проектировать ИИ NPC для Roblox: поиск пути, преследование и атаки, восприятие целей и поведение с состояниями. Также описывает работу с большим числом NPC.

Где нужно рассчитывать путь NPC в Roblox?

На сервере: на клиенте поиск пути учитывает только геометрию, загруженную этим клиентом.

Исходный текст

SKILL.md · MIT
---
name: roblox-npc-ai
description: NPCs and enemy AI - PathfindingService (CreatePath, ComputeAsync, costs, modifiers, links, blocked paths), chase/follow loops, state machines, perception and line of sight, spawning/pooling, scaling to many NPCs. Use when creating enemies, pets, followers, shopkeepers, wave spawners, or fixing NPCs that get stuck, jitter, or lag the server.
---

# NPCs and AI

## Architecture

- NPC **logic runs on the server** (authoritative targets, damage, drops). Visual extras (idle
  animations, nameplates, effects) can run on clients.
- One NPC service drives all NPCs from a single loop (e.g. 5–10 Hz "think" rate, staggered), not one
  script + `while true` per NPC. Tag NPC models (`CollectionService`) and keep per-NPC state in a table.
- Server-owned physics: `npc.PrimaryPart:SetNetworkOwner(nil)` after spawning, so NPCs don't stutter
  when ownership moves between nearby players (and exploiters can't push them).
- Use `Humanoid` for NPCs that need walking/jumping/climbing; for simple movers (turrets, floating
  enemies, crowds) use an `AnimationController` + `Animator` and move with constraints or CFrames.

## Pathfinding

```luau
--!strict
local PathfindingService = game:GetService("PathfindingService")

local path = PathfindingService:CreatePath({
	AgentRadius = 2,
	AgentHeight = 5,
	AgentCanJump = true,
	AgentCanClimb = false,
	WaypointSpacing = 4,
	Costs = {
		Water = 20, -- avoid water (Enum.Material name)
		DangerZone = math.huge, -- PathfindingModifier.Label: never cross
	},
})

-- Walk `humanoid` to `goal`. Returns true on arrival, false if unreachable or interrupted.
local function walkTo(humanoid: Humanoid, goal: Vector3): boolean
	local root = humanoid.RootPart
	if not root then
		return false
	end
	local ok = pcall(function()
		path:ComputeAsync(root.Position, goal)
	end)
	if not ok or path.Status ~= Enum.PathStatus.Success then
		return false -- NoPath: try a fallback (direct MoveTo, new goal, teleport if stuck long)
	end

	local waypoints = path:GetWaypoints()
	local blocked = false
	local blockedConnection = path.Blocked:Connect(function(blockedIndex)
		blocked = true -- an obstacle appeared on a waypoint ahead; caller recomputes
		print("path blocked at waypoint", blockedIndex)
	end)

	for index = 2, #waypoints do
		local waypoint = waypoints[index]
		if waypoint.Action == Enum.PathWaypointAction.Jump then
			humanoid.Jump = true
		end
		humanoid:MoveTo(waypoint.Position)
		local reached = humanoid.MoveToFinished:Wait() -- false after 8 s timeout
		if not reached or blocked or humanoid.Health <= 0 then
			blockedConnection:Disconnect()
			return false
		end
	end
	blockedConnection:Disconnect()
	return true
end

return walkTo
```

- `CreatePath` + `ComputeAsync` is the current API (`FindPathAsync` is superseded). Reuse `Path` objects
  per agent type; `ComputeAsync` yields — never call it every frame for every NPC.
- **Chasing moving targets**: recompute when the target moved more than a few studs since the last
  compute or every ~0.5–1 s, and skip pathfinding entirely when there's a clear line of sight
  (`workspace:Raycast` from NPC to target) — just `MoveTo` the target.
- `PathfindingModifier` (child of a part/region, `Label` matching a `Costs` key, `PassThrough` for doors)
  and `PathfindingLink` (between two attachments, e.g. ladders, teleporters, boats; the waypoint has
  `Label` and `Action = Custom`) shape paths.
- Limits: start→goal straight-line distance ≤ 3,000 studs, 20,000-node budget; far goals need
  intermediate targets. Visualize the navmesh with Studio's **Navigation Mesh** visualization option.
- On clients, pathfinding sees only streamed-in geometry: compute paths on the server.

## Behavior: state machine

```luau
--!strict
type State = "Idle" | "Chase" | "Attack" | "Return"

type Npc = {
	model: Model,
	humanoid: Humanoid,
	home: Vector3,
	state: State,
	target: Model?,
	lastAttack: number,
}

local AGGRO_RANGE = 40
local ATTACK_RANGE = 5
local LEASH_RANGE = 80
local ATTACK_COOLDOWN = 1.2

local losParams = RaycastParams.new()
losParams.FilterType = Enum.RaycastFilterType.Exclude

local function hasLineOfSight(from: Vector3, target: BasePart, ignore: { Instance }): boolean
	losParams.FilterDescendantsInstances = ignore
	local result = workspace:Raycast(from, target.Position - from, losParams)
	return result == nil or result.Instance:IsDescendantOf(target.Parent :: Instance)
end

local function think(npc: Npc, findTarget: (Vector3, number) -> Model?)
	local root = npc.humanoid.RootPart
	if not root or npc.humanoid.Health <= 0 then
		return
	end
	local targetRoot = npc.target and npc.target:FindFirstChild("HumanoidRootPart") :: BasePart?
	local distance = if targetRoot then (targetRoot.Position - root.Position).Magnitude else math.huge

	if npc.state == "Idle" then
		npc.target = findTarget(root.Position, AGGRO_RANGE)
		if npc.target then
			npc.state = "Chase"
		end
	elseif npc.state == "Chase" then
		if not targetRoot or (root.Position - npc.home).Magnitude > LEASH_RANGE then
			npc.state = "Return"
		elseif distance <= ATTACK_RANGE then
			npc.state = "Attack"
		elseif hasLineOfSight(root.Position, targetRoot, { npc.model }) then
			npc.humanoid:MoveTo(targetRoot.Position)
		end -- else: request a path (throttled) via walkTo in a separate thread
	elseif npc.state == "Attack" then
		if not targetRoot or distance > ATTACK_RANGE * 1.5 then
			npc.state = "Chase"
		elseif os.clock() - npc.lastAttack >= ATTACK_COOLDOWN then
			npc.lastAttack = os.clock()
			local targetHumanoid = npc.target and npc.target:FindFirstChildOfClass("Humanoid")
			if targetHumanoid then
				targetHumanoid:TakeDamage(10)
			end
		end
	elseif npc.state == "Return" then
		npc.target = nil
		npc.humanoid:MoveTo(npc.home)
		if (root.Position - npc.home).Magnitude < 4 then
			npc.state = "Idle"
		end
	end
end

return think
```

For complex AI (many behaviors, priorities), use a behavior tree or utility AI; keep the same "think
at a fixed rate, act through small primitives" structure. See [references/scaling-npcs.md](references/scaling-npcs.md)
for spawning, pooling, and performance with hundreds of NPCs.

## Perception tips

- Find targets with `workspace:GetPartBoundsInRadius` against a collision group/filter containing only
  characters, or iterate `Players:GetPlayers()` (cheaper for small counts) and compare squared distances.
- Add reaction delays and field-of-view checks (`root.CFrame.LookVector:Dot(direction.Unit) > 0.5`)
  so NPCs feel fair.
- Stagger thinking: `npcIndex % 5 == frame % 5` spreads work across frames.

## Related skills

`roblox-characters-animation` (humanoids, animation), `roblox-physics` (ownership, raycasts),
`roblox-performance` (profiling, parallel Luau), `roblox-game-systems` (waves, combat, drops).

© EL4CTEO · MIT · EL4CTEO/roblox-skills

Похожие скиллы

Все скиллы по теме «Геймдев и 3D: Unity, Unreal, Godot, Blender» →

Сначала — roblox-npc-ai от других авторов.

roblox-npc-ai TabooHarmony Скилл roblox-npc-ai для Claude Code, Codex, Cursor, Copilot, Gemini CLI и OpenCode. Добавляет агенту знание Roblox PathfindingService, машин состояний для NPC, линии видимости и серверных AI-петель. CX Codex +1 3 400установок roblox-npcs nonlooped Скилл roblox-npcs для Claude Code создаёт и отлаживает навигацию NPC в Roblox через PathfindingService. Настраивает патрулирование, преследование и обход препятствий. CX Codex +1 518установок scenario-roblox-gameplay scenario-labs Скилл scenario-roblox-gameplay для Claude Code помогает собирать игровые системы Roblox: ИИ NPC, боевые механики, снаряды и транспорт. Включается при разработке логики геймплея и разборе проблем с путями NPC, хитбоксами или физикой машин. CX Codex +1 357установок game-ai gamedev-skills Скилл game-ai для Claude Code помогает проектировать и отлаживать искусственный интеллект для врагов и NPC, независимый от игрового движка. CX Codex +1 14 100установок godot-navigation-pathfinding thedivergentai Скилл godot-navigation-pathfinding учит ИИ-агента строить поиск путей и логику перемещения в Godot без просадок FPS. Помогает при создании NPC в стратегиях, стелс-играх и Tower Defense. CX Codex +1 499установок mm2-roblox-analytics-tracker reason-machines Скилл mm2-roblox-analytics-tracker для Claude Code собирает аналитику Murder Mystery 2, отслеживает инвентарь и разбирает игровые показатели. Анализирует статистику и коллекцию ножей. CX Codex +1 2 300установок mm2-analytics-roblox-toolkit reason-machines Скилл mm2-analytics-roblox-toolkit для Claude Code, Codex, Cursor и других агентов, который подключает аналитику Murder Mystery 2 из Roblox. Помогает отслеживать инвентарь, считать статистику матчей и экспортировать данные в CSV или JSON. CX Codex +1 2 300установок

Из того же набора22

Весь набор →
roblox-open-cloud Скилл roblox-open-cloud для Claude Code помогает работать с Open Cloud API Roblox и HttpService. Включается при создании внешних инструментов, ботов и CI/CD для игр. CX Codex +1 1 200установок roblox-text-chat Скилл roblox-text-chat для Claude Code и Cursor, который настраивает TextChatService, фильтрацию текста и чат в Roblox. Включается при добавлении чата, команд или табличек с текстом игроков. CX Codex +1 1 200установок roblox-monetization Скилл roblox-monetization для Claude Code помогает настраивать монетизацию в Roblox и разбирать сбои покупок. Подключается при работе с магазинами, пропусками, подписками, рекламой и платными случайными предметами. CX Codex +1 1 200установок roblox-physics Скилл roblox-physics для Claude Code управляет физикой и пространственными запросами. Подключается при настройке столкновений, лучей и транспорта. CX Codex +1 1 200установок roblox-teleport-matchmaking Скилл roblox-teleport-matchmaking для Claude Code управляет телепортацией игроков и созданием матчей в Roblox через TeleportService. CX Codex +1 1 200установок roblox-input Скилл roblox-input для Claude Code настраивает ввод игрока и камеры в Roblox. Он подключается к задачам с клавишами, способностями, транспортом, сенсорными кнопками или собственной камерой. CX Codex +1 1 200установок roblox-analytics-liveops Скилл roblox-analytics-liveops для Claude Code настраивает игровую аналитику, воронки, экономику и live-ops на Lua. Включается при добавлении событий, A/B-тестов или начислении наград. CX Codex +1 1 200установок roblox-audio Скилл roblox-audio для Claude Code помогает настраивать звук в Roblox: музыку, эффекты и пространственное аудио. Включается при добавлении звука или поиске причины, по которой он не воспроизводится. CX Codex +1 1 200установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой