Нужно написать код lua для роблокс студио который ...

تم الإنشاء في: ٢٩ مايو ٢٠٢٥

تمت الإجابة باستخدام O3 بواسطة Chat01

سؤال

Нужно написать код lua для роблокс студио который будет вставлен в НПС, в коде НПС будет преследовать ближайшего игрока, и если НПС застрянет на месте или не дойдет к игроку и будет проверять правильной путь и опять идти к ближайшему игрока

الفكرة

Writing NPC pathfinding script

The user needs a Lua script for Roblox where an NPC chases the nearest player and recalculates its path if stuck. I'll write a Lua snippet using Roblox's PathfindingService to handle the chasing and path recalculation. The NPC will monitor its path status and, if needed, check if it's stuck and re-calculate the path to the nearest player. I'll include the necessary functions to move the NPC and ensure smooth navigation using the humanoid. Let me get started on this code!

Writing pathfinding code

I'll write a script that checks when the humanoid of an NPC hasn't moved for a while or when the path is blocked. Using PathfindingService, I'll create a function where the NPC’s velocity is monitored. If the velocity drops below a threshold for a set period, it'll trigger a path recalculation. I'll explain the logic step by step in Russian and include the code in a markdown code block. That way, the user gets everything in a clean, understandable format.

Thought for 34 seconds

الإجابة

Вот пример готового скрипта (Lua) для NPC в Roblox Studio.
Скрипт вставьте в ServerScriptService или внутрь самой модели-NPC (Script или LocalScript не нужен – только обычный Script на сервере).
NPC будет:

  1. Находить ближайшего живого игрока.
  2. Строить к нему путь через PathfindingService.
  3. Следовать по путевым точкам.
  4. Если путь блокируется или NPC практически не движется STUCK_TIME секунд, путь пересчитывается заново, и цикл повторяется.
lua
--[[ Скрипт «Охотник» для NPC Автор: ChatGPT (29.05.2025) ]] --------------------------------------------------------------------- -- НАСТРОЙКИ --------------------------------------------------------------------- local STUCK_TIME = 2 -- Секунд без движения до признания «застрял» local PATH_RETRY_DELAY = 0.1 -- Пауза между пересчётами local END_REACHED_DIST = 2 -- Считаем, что NPC дошёл до игрока --------------------------------------------------------------------- local npc = script.Parent -- Модель NPC local humanoid = npc:WaitForChild("Humanoid") local rootPart = npc:WaitForChild("HumanoidRootPart") local PathService = game:GetService("PathfindingService") local Players = game:GetService("Players") local RunService = game:GetService("RunService") --------------------------------------------------------------------- -- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ --------------------------------------------------------------------- local function getNearestCharacter() local nearestChar, nearestDist = nil, math.huge for _, plr in ipairs(Players:GetPlayers()) do local char = plr.Character if char and char:FindFirstChild("HumanoidRootPart") then local hrp = char.HumanoidRootPart if char:FindFirstChildOfClass("Humanoid").Health > 0 then local dist = (hrp.Position - rootPart.Position).Magnitude if dist < nearestDist then nearestDist, nearestChar = dist, char end end end end return nearestChar, nearestDist end local function follow(targetChar) if not targetChar or not targetChar:FindFirstChild("HumanoidRootPart") then return end local path = PathService:CreatePath({ AgentRadius = 2, AgentHeight = 5, AgentCanJump = true, WaypointSpacing = 2 }) path:ComputeAsync(rootPart.Position, targetChar.HumanoidRootPart.Position) if path.Status ~= Enum.PathStatus.Success then return end local waypoints = path:GetWaypoints() local wpIndex = 1 local stuckTime = 0 local lastPos = rootPart.Position -- Коллбек при блокировке пути local blockedConn blockedConn = path.Blocked:Connect(function(blockedIndex) if blockedIndex >= wpIndex then blockedConn:Disconnect() wpIndex = #waypoints + 1 -- прерываем цикл - вызовется пересчёт end end) -- Отслеживание перемещения и переход между точками local mover mover = RunService.Heartbeat:Connect(function(dt) if wpIndex > #waypoints then mover:Disconnect() return end local currentWP = waypoints[wpIndex] -- Проверка достижения текущей точки if (rootPart.Position - currentWP.Position).Magnitude < 1 then wpIndex += 1 local nextWP = waypoints[wpIndex] if nextWP then if nextWP.Action == Enum.PathWaypointAction.Jump then humanoid:ChangeState(Enum.HumanoidStateType.Jumping) end humanoid:MoveTo(nextWP.Position) end end -- Проверка «застрял?» if (rootPart.Position - lastPos).Magnitude < 0.1 then stuckTime += dt if stuckTime >= STUCK_TIME then mover:Disconnect() end else stuckTime = 0 end lastPos = rootPart.Position end) -- Стартовое движение if #waypoints > 0 then humanoid:MoveTo(waypoints[1].Position) end -- Ожидаем завершения перехода или прерывания while mover.Connected do if not targetChar.Parent or targetChar.Humanoid.Health <= 0 then mover:Disconnect() break -- цель умерла/удалена end if (rootPart.Position - targetChar.HumanoidRootPart.Position).Magnitude < END_REACHED_DIST then -- NPC дошёл до игрока – остановка (здесь можно добавить атаку) humanoid:MoveTo(rootPart.Position) mover:Disconnect() break end task.wait() -- освобождаем поток end if blockedConn.Connected then blockedConn:Disconnect() end end --------------------------------------------------------------------- -- ГЛАВНЫЙ ЦИКЛ --------------------------------------------------------------------- while task.wait(PATH_RETRY_DELAY) do local targetChar = getNearestCharacter() if targetChar then follow(targetChar) -- функция сама вернётся, если путь прервётся/застрянет end end

Как использовать

  1. Создайте NPC-модель (Rig + Humanoid) и вставьте в неё Script с кодом выше.
  2. Убедитесь, что у NPC есть:
    • Humanoid
    • HumanoidRootPart
  3. Отрегулируйте константы в блоке НАСТРОЙКИ под свои нужды:
    • STUCK_TIME – за сколько секунд «неподвижности» NPC считает себя застрявшим.
    • END_REACHED_DIST – дистанция, при которой NPC считает, что «поймал» игрока (можно там запускать анимацию атаки).
  4. Запустите игру - NPC автоматически найдёт ближайшего игрока и начнёт преследование, пересчитывая маршрут при необходимости.

💡 Совет: если хотите добавить анимации или «урон» игроку – вставьте логику в блок, где проверяется расстояние END_REACHED_DIST.

مشاركة هذا السؤال والجواب