Hasli4

Untitled

Sep 2nd, 2026
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 16.88 KB | None | 0 0
  1. local Players = game:GetService("Players")
  2. local ReplicatedStorage = game:GetService("ReplicatedStorage")
  3. local TextService = game:GetService("TextService")
  4. local PathfindingService = game:GetService("PathfindingService")
  5. local PhysicsService = game:GetService("PhysicsService")
  6.  
  7.  
  8. --------------------------------------------------
  9. -- RemoteEvents
  10. --------------------------------------------------
  11.  
  12. local submitPlayerName =
  13.     ReplicatedStorage:WaitForChild("SubmitPlayerName")
  14.  
  15. local showDialogResponse =
  16.     ReplicatedStorage:WaitForChild("ShowDialogResponse")
  17.  
  18.  
  19. --------------------------------------------------
  20. -- NPC
  21. --------------------------------------------------
  22.  
  23. local npc =
  24.     workspace:WaitForChild("NPC")
  25.  
  26. local humanoid =
  27.     npc:WaitForChild("Humanoid")
  28.  
  29. local rootPart =
  30.     npc:WaitForChild("HumanoidRootPart")
  31.  
  32.  
  33. --------------------------------------------------
  34. -- NPC PATH
  35. --------------------------------------------------
  36.  
  37. local npcPath =
  38.     workspace:WaitForChild("NPCPath")
  39.  
  40. local startPoint =
  41.     npcPath:WaitForChild("Start")
  42.  
  43. local middlePoint =
  44.     npcPath:WaitForChild("Middle")
  45.  
  46. local doorPoint =
  47.     npcPath:WaitForChild("Door")
  48.  
  49. local cornerPoint =
  50.     npcPath:WaitForChild("Corner")
  51.  
  52.  
  53. --------------------------------------------------
  54. -- SETTINGS
  55. --------------------------------------------------
  56.  
  57. local RESPONSE_DURATION = 3
  58.  
  59. local WALK_SPEED = 8
  60.  
  61. local AGENT_RADIUS = 2
  62.  
  63. local AGENT_HEIGHT = 5
  64.  
  65. local MAX_REPATH_ATTEMPTS = 5
  66.  
  67.  
  68. --------------------------------------------------
  69. -- STATE
  70. --------------------------------------------------
  71.  
  72. local playerNames = {}
  73.  
  74. local npcLeaving = false
  75.  
  76. local npcGone = false
  77.  
  78.  
  79. --------------------------------------------------
  80. -- HUMANOID SETTINGS
  81. --------------------------------------------------
  82.  
  83. humanoid.WalkSpeed = WALK_SPEED
  84. humanoid.AutoRotate = true
  85. humanoid.AutoJumpEnabled = false
  86.  
  87.  
  88. --------------------------------------------------
  89. -- ANIMATION
  90. --
  91. -- Используем уже существующую:
  92. --
  93. -- NPC
  94. -- └── Animate
  95. --     └── walk
  96. --         └── WalkAnim
  97. --------------------------------------------------
  98.  
  99. local animateScript =
  100.     npc:WaitForChild("Animate")
  101.  
  102. local walkFolder =
  103.     animateScript:WaitForChild("walk")
  104.  
  105. local walkAnimation =
  106.     walkFolder:WaitForChild("WalkAnim")
  107.  
  108.  
  109. print("[NPC] Найдена стандартная WalkAnim:")
  110. print("[NPC]", walkAnimation.AnimationId)
  111.  
  112.  
  113. --------------------------------------------------
  114. -- Animator
  115. --------------------------------------------------
  116.  
  117. local animator =
  118.     humanoid:FindFirstChildOfClass("Animator")
  119.  
  120.  
  121. if not animator then
  122.  
  123.     animator = Instance.new("Animator")
  124.     animator.Parent = humanoid
  125.  
  126. end
  127.  
  128.  
  129. --------------------------------------------------
  130. -- Загружаем существующую R6 walk-анимацию
  131. --------------------------------------------------
  132.  
  133. local walkTrack
  134.  
  135. local animationSuccess, animationError =
  136.     pcall(function()
  137.  
  138.         walkTrack =
  139.             animator:LoadAnimation(
  140.                 walkAnimation
  141.             )
  142.  
  143.     end)
  144.  
  145.  
  146. if not animationSuccess then
  147.  
  148.     warn(
  149.         "[NPC] Не удалось загрузить WalkAnim:",
  150.         animationError
  151.     )
  152.  
  153. else
  154.  
  155.     walkTrack.Looped = true
  156.  
  157.     walkTrack.Priority =
  158.         Enum.AnimationPriority.Movement
  159.  
  160.     print("[NPC] WalkAnim успешно загружена")
  161.  
  162. end
  163.  
  164.  
  165. --------------------------------------------------
  166. -- Запуск ходьбы
  167. --------------------------------------------------
  168.  
  169. local function startWalkingAnimation()
  170.  
  171.     if not walkTrack then
  172.         return
  173.     end
  174.  
  175.     if not walkTrack.IsPlaying then
  176.  
  177.         walkTrack:Play(
  178.             0.15,
  179.             1,
  180.             1
  181.         )
  182.  
  183.     end
  184.  
  185. end
  186.  
  187.  
  188. --------------------------------------------------
  189. -- Остановка ходьбы
  190. --------------------------------------------------
  191.  
  192. local function stopWalkingAnimation()
  193.  
  194.     if not walkTrack then
  195.         return
  196.     end
  197.  
  198.     if walkTrack.IsPlaying then
  199.  
  200.         walkTrack:Stop(0.15)
  201.  
  202.     end
  203.  
  204. end
  205.  
  206.  
  207. --------------------------------------------------
  208. -- СОЗДАЁМ COLLISION GROUP
  209. --
  210. -- NPC не сталкивается с игроками.
  211. --------------------------------------------------
  212.  
  213. local NPC_GROUP = "NPC"
  214.  
  215. local successCollisionGroup =
  216.     pcall(function()
  217.  
  218.         PhysicsService:RegisterCollisionGroup(
  219.             NPC_GROUP
  220.         )
  221.  
  222.     end)
  223.  
  224.  
  225. --------------------------------------------------
  226. -- NPC НЕ СТОЛКАИВАЕТСЯ С PLAYER
  227. --------------------------------------------------
  228.  
  229. pcall(function()
  230.  
  231.     PhysicsService:CollisionGroupSetCollidable(
  232.         NPC_GROUP,
  233.         "Default",
  234.         true
  235.     )
  236.  
  237. end)
  238.  
  239.  
  240. --------------------------------------------------
  241. -- Определяем collision group для частей NPC
  242. --------------------------------------------------
  243.  
  244. for _, object in ipairs(npc:GetDescendants()) do
  245.  
  246.     if object:IsA("BasePart") then
  247.  
  248.         object.CollisionGroup = NPC_GROUP
  249.  
  250.     end
  251.  
  252. end
  253.  
  254.  
  255. --------------------------------------------------
  256. -- Игроки тоже не сталкиваются с NPC
  257. --------------------------------------------------
  258.  
  259. local function setupPlayerCollision(character)
  260.  
  261.     for _, object in ipairs(character:GetDescendants()) do
  262.  
  263.         if object:IsA("BasePart") then
  264.  
  265.             PhysicsService:CollisionGroupSetCollidable(
  266.                 NPC_GROUP,
  267.                 object.CollisionGroup,
  268.                 false
  269.             )
  270.  
  271.         end
  272.  
  273.     end
  274.  
  275. end
  276.  
  277.  
  278. --------------------------------------------------
  279. -- PATHFINDING
  280. --------------------------------------------------
  281.  
  282. local function createPath()
  283.  
  284.     return PathfindingService:CreatePath({
  285.  
  286.         AgentRadius = AGENT_RADIUS,
  287.  
  288.         AgentHeight = AGENT_HEIGHT,
  289.  
  290.         AgentCanJump = false,
  291.  
  292.         AgentCanClimb = false,
  293.  
  294.     })
  295.  
  296. end
  297.  
  298.  
  299. --------------------------------------------------
  300. -- Движение по вычисленному пути
  301. --------------------------------------------------
  302.  
  303. local function followPathTo(targetPosition)
  304.  
  305.     if npcGone then
  306.         return false
  307.     end
  308.  
  309.  
  310.     --------------------------------------------------
  311.     -- Создаём путь
  312.     --------------------------------------------------
  313.  
  314.     local path =
  315.         createPath()
  316.  
  317.  
  318.     local success =
  319.         pcall(function()
  320.  
  321.             path:ComputeAsync(
  322.                 rootPart.Position,
  323.                 targetPosition
  324.             )
  325.  
  326.         end)
  327.  
  328.  
  329.     if not success then
  330.  
  331.         warn(
  332.             "[NPC] Ошибка ComputeAsync"
  333.         )
  334.  
  335.         return false
  336.  
  337.     end
  338.  
  339.  
  340.     --------------------------------------------------
  341.     -- Проверяем путь
  342.     --------------------------------------------------
  343.  
  344.     if path.Status ~= Enum.PathStatus.Success then
  345.  
  346.         warn(
  347.             "[NPC] Pathfinding не нашёл путь к точке"
  348.         )
  349.  
  350.         return false
  351.  
  352.     end
  353.  
  354.  
  355.     local waypoints =
  356.         path:GetWaypoints()
  357.  
  358.  
  359.     print(
  360.         "[NPC] Найдено waypoint:",
  361.         #waypoints
  362.     )
  363.  
  364.  
  365.     --------------------------------------------------
  366.     -- Индекс текущего waypoint
  367.     --------------------------------------------------
  368.  
  369.     local currentWaypointIndex = 1
  370.  
  371.  
  372.     --------------------------------------------------
  373.     -- Обрабатываем блокировку пути
  374.     --------------------------------------------------
  375.  
  376.     local pathBlocked = false
  377.  
  378.     local blockedConnection
  379.  
  380.     blockedConnection =
  381.         path.Blocked:Connect(
  382.             function(blockedWaypointIndex)
  383.  
  384.                 if blockedWaypointIndex >=
  385.                     currentWaypointIndex then
  386.  
  387.                     pathBlocked = true
  388.  
  389.                 end
  390.  
  391.             end
  392.         )
  393.  
  394.  
  395.     --------------------------------------------------
  396.     -- Начинаем ходьбу
  397.     --------------------------------------------------
  398.  
  399.     startWalkingAnimation()
  400.  
  401.  
  402.     --------------------------------------------------
  403.     -- Идём по waypoint
  404.     --------------------------------------------------
  405.  
  406.     while currentWaypointIndex <= #waypoints do
  407.  
  408.         if npcGone then
  409.             break
  410.         end
  411.  
  412.  
  413.         --------------------------------------------------
  414.         -- Если путь заблокирован
  415.         --------------------------------------------------
  416.  
  417.         if pathBlocked then
  418.  
  419.             print(
  420.                 "[NPC] Путь заблокирован, пересчитываю"
  421.             )
  422.  
  423.             blockedConnection:Disconnect()
  424.  
  425.             return false
  426.  
  427.         end
  428.  
  429.  
  430.         local waypoint =
  431.             waypoints[currentWaypointIndex]
  432.  
  433.  
  434.         --------------------------------------------------
  435.         -- Waypoint может требовать прыжок
  436.         --------------------------------------------------
  437.  
  438.         if waypoint.Action ==
  439.             Enum.PathWaypointAction.Jump then
  440.  
  441.             humanoid.Jump = true
  442.  
  443.         end
  444.  
  445.  
  446.         --------------------------------------------------
  447.         -- Двигаемся к waypoint
  448.         --------------------------------------------------
  449.  
  450.         humanoid:MoveTo(
  451.             waypoint.Position
  452.         )
  453.  
  454.  
  455.         local reached =
  456.             humanoid.MoveToFinished:Wait()
  457.  
  458.  
  459.         if not reached then
  460.  
  461.             print(
  462.                 "[NPC] Waypoint не достигнут"
  463.             )
  464.  
  465.             blockedConnection:Disconnect()
  466.  
  467.             return false
  468.  
  469.         end
  470.  
  471.  
  472.         currentWaypointIndex += 1
  473.  
  474.     end
  475.  
  476.  
  477.     --------------------------------------------------
  478.     -- Отключаем обработчик
  479.     --------------------------------------------------
  480.  
  481.     if blockedConnection then
  482.         blockedConnection:Disconnect()
  483.     end
  484.  
  485.  
  486.     return true
  487.  
  488. end
  489.  
  490.  
  491. --------------------------------------------------
  492. -- Идём к конкретной контрольной точке
  493. --------------------------------------------------
  494.  
  495. local function moveToPoint(point)
  496.  
  497.     if npcGone then
  498.         return false
  499.     end
  500.  
  501.  
  502.     print(
  503.         "========================================"
  504.     )
  505.  
  506.     print(
  507.         "[NPC] ИДУ К:",
  508.         point.Name
  509.     )
  510.  
  511.  
  512.     --------------------------------------------------
  513.     -- Несколько попыток
  514.     --------------------------------------------------
  515.  
  516.     for attempt = 1, MAX_REPATH_ATTEMPTS do
  517.  
  518.         if npcGone then
  519.             return false
  520.         end
  521.  
  522.  
  523.         print(
  524.             "[NPC] Попытка:",
  525.             attempt,
  526.             "/",
  527.             MAX_REPATH_ATTEMPTS
  528.         )
  529.  
  530.  
  531.         local success =
  532.             followPathTo(
  533.                 point.Position
  534.             )
  535.  
  536.  
  537.         if success then
  538.  
  539.             print(
  540.                 "[NPC] Достиг:",
  541.                 point.Name
  542.             )
  543.  
  544.             return true
  545.  
  546.         end
  547.  
  548.  
  549.         --------------------------------------------------
  550.         -- Небольшая пауза перед пересчётом
  551.         --------------------------------------------------
  552.  
  553.         task.wait(0.2)
  554.  
  555.     end
  556.  
  557.  
  558.     warn(
  559.         "[NPC] Не удалось достичь:",
  560.         point.Name
  561.     )
  562.  
  563.     return false
  564.  
  565. end
  566.  
  567.  
  568. --------------------------------------------------
  569. -- УХОД NPC
  570. --------------------------------------------------
  571.  
  572. local function makeNpcLeave()
  573.  
  574.     if npcLeaving then
  575.         return
  576.     end
  577.  
  578.     if npcGone then
  579.         return
  580.     end
  581.  
  582.  
  583.     npcLeaving = true
  584.  
  585.  
  586.     print("========================================")
  587.     print("[NPC] НАЧИНАЮ УХОД")
  588.     print("========================================")
  589.  
  590.  
  591.     --------------------------------------------------
  592.     -- Start
  593.     --------------------------------------------------
  594.  
  595.     local reachedStart =
  596.         moveToPoint(startPoint)
  597.  
  598.  
  599.     if not reachedStart then
  600.  
  601.         warn(
  602.             "[NPC] Start не достигнут"
  603.         )
  604.  
  605.     end
  606.  
  607.  
  608.     --------------------------------------------------
  609.     -- Middle
  610.     --------------------------------------------------
  611.  
  612.     local reachedMiddle =
  613.         moveToPoint(middlePoint)
  614.  
  615.  
  616.     if not reachedMiddle then
  617.  
  618.         warn(
  619.             "[NPC] Middle не достигнут"
  620.         )
  621.  
  622.     end
  623.  
  624.  
  625.     --------------------------------------------------
  626.     -- Door
  627.     --------------------------------------------------
  628.  
  629.     local reachedDoor =
  630.         moveToPoint(doorPoint)
  631.  
  632.  
  633.     if not reachedDoor then
  634.  
  635.         warn(
  636.             "[NPC] Door не достигнут"
  637.         )
  638.  
  639.     end
  640.  
  641.  
  642.     --------------------------------------------------
  643.     -- Corner
  644.     --------------------------------------------------
  645.  
  646.     local reachedCorner =
  647.         moveToPoint(cornerPoint)
  648.  
  649.  
  650.     if not reachedCorner then
  651.  
  652.         warn(
  653.             "[NPC] Corner не достигнут"
  654.         )
  655.  
  656.     end
  657.  
  658.  
  659.     --------------------------------------------------
  660.     -- Останавливаем анимацию
  661.     --------------------------------------------------
  662.  
  663.     stopWalkingAnimation()
  664.  
  665.  
  666.     --------------------------------------------------
  667.     -- NPC исчезает
  668.     --------------------------------------------------
  669.  
  670.     if npc.Parent then
  671.  
  672.         print(
  673.             "[NPC] Достиг Corner"
  674.         )
  675.  
  676.         print(
  677.             "[NPC] NPC исчезает"
  678.         )
  679.  
  680.         npcGone = true
  681.  
  682.         npc:Destroy()
  683.  
  684.     end
  685.  
  686. end
  687.  
  688.  
  689. --------------------------------------------------
  690. -- ПОЛУЧЕНИЕ ИМЕНИ
  691. --------------------------------------------------
  692.  
  693. submitPlayerName.OnServerEvent:Connect(
  694.     function(player, rawName)
  695.  
  696.         print("========================================")
  697.         print("[DIALOG SERVER] Получено имя")
  698.         print("[DIALOG SERVER] Игрок:", player.Name)
  699.         print("[DIALOG SERVER] UserId:", player.UserId)
  700.         print("[DIALOG SERVER] Имя:", rawName)
  701.         print("========================================")
  702.  
  703.  
  704.         --------------------------------------------------
  705.         -- NPC уже уходит
  706.         --------------------------------------------------
  707.  
  708.         if npcLeaving or npcGone then
  709.  
  710.             warn(
  711.                 "[DIALOG SERVER] NPC уже уходит"
  712.             )
  713.  
  714.             return
  715.  
  716.         end
  717.  
  718.  
  719.         --------------------------------------------------
  720.         -- Проверяем тип
  721.         --------------------------------------------------
  722.  
  723.         if typeof(rawName) ~= "string" then
  724.  
  725.             warn(
  726.                 "[DIALOG SERVER] Имя не строка"
  727.             )
  728.  
  729.             return
  730.  
  731.         end
  732.  
  733.  
  734.         --------------------------------------------------
  735.         -- Убираем пробелы
  736.         --------------------------------------------------
  737.  
  738.         rawName =
  739.             rawName:match("^%s*(.-)%s*$")
  740.  
  741.  
  742.         --------------------------------------------------
  743.         -- Проверяем пустоту
  744.         --------------------------------------------------
  745.  
  746.         if rawName == "" then
  747.  
  748.             warn(
  749.                 "[DIALOG SERVER] Игрок отправил пустое имя"
  750.             )
  751.  
  752.             return
  753.  
  754.         end
  755.  
  756.  
  757.         --------------------------------------------------
  758.         -- Максимум 20 символов
  759.         --------------------------------------------------
  760.  
  761.         local length =
  762.             utf8.len(rawName)
  763.  
  764.  
  765.         if not length then
  766.  
  767.             warn(
  768.                 "[DIALOG SERVER] Некорректный UTF-8"
  769.             )
  770.  
  771.             return
  772.  
  773.         end
  774.  
  775.  
  776.         if length > 20 then
  777.  
  778.             local cutPosition =
  779.                 utf8.offset(rawName, 21)
  780.  
  781.             if cutPosition then
  782.  
  783.                 rawName =
  784.                     string.sub(
  785.                         rawName,
  786.                         1,
  787.                         cutPosition - 1
  788.                     )
  789.  
  790.             end
  791.  
  792.         end
  793.  
  794.  
  795.         --------------------------------------------------
  796.         -- Фильтрация
  797.         --------------------------------------------------
  798.  
  799.         print(
  800.             "[DIALOG SERVER] Фильтруем имя..."
  801.         )
  802.  
  803.  
  804.         local success, filterResult =
  805.             pcall(function()
  806.  
  807.                 return TextService:FilterStringAsync(
  808.                     rawName,
  809.                     player.UserId
  810.                 )
  811.  
  812.             end)
  813.  
  814.  
  815.         if not success then
  816.  
  817.             warn(
  818.                 "[DIALOG SERVER] FilterStringAsync:",
  819.                 filterResult
  820.             )
  821.  
  822.             return
  823.  
  824.         end
  825.  
  826.  
  827.         --------------------------------------------------
  828.         -- Получаем безопасный текст
  829.         --------------------------------------------------
  830.  
  831.         local successFiltered, filteredName =
  832.             pcall(function()
  833.  
  834.                 return filterResult:GetNonChatStringForUserAsync(
  835.                     player.UserId
  836.                 )
  837.  
  838.             end)
  839.  
  840.  
  841.         if not successFiltered then
  842.  
  843.             warn(
  844.                 "[DIALOG SERVER] Ошибка фильтрации:",
  845.                 filteredName
  846.             )
  847.  
  848.             return
  849.  
  850.         end
  851.  
  852.  
  853.         --------------------------------------------------
  854.         -- Проверяем результат
  855.         --------------------------------------------------
  856.  
  857.         if typeof(filteredName) ~= "string" then
  858.  
  859.             warn(
  860.                 "[DIALOG SERVER] filteredName не строка"
  861.             )
  862.  
  863.             return
  864.  
  865.         end
  866.  
  867.  
  868.         if filteredName == "" then
  869.  
  870.             warn(
  871.                 "[DIALOG SERVER] После фильтрации имя пустое"
  872.             )
  873.  
  874.             return
  875.  
  876.         end
  877.  
  878.  
  879.         --------------------------------------------------
  880.         -- Сохраняем имя
  881.         --------------------------------------------------
  882.  
  883.         playerNames[player.UserId] =
  884.             filteredName
  885.  
  886.  
  887.         print(
  888.             "[DIALOG SERVER] Имя сохранено:",
  889.             filteredName
  890.         )
  891.  
  892.  
  893.         --------------------------------------------------
  894.         -- Формируем ответ
  895.         --------------------------------------------------
  896.  
  897.         local response =
  898.             "Понятно, " .. filteredName .. "."
  899.  
  900.  
  901.         print(
  902.             "[DIALOG SERVER] Отправляем:",
  903.             response
  904.         )
  905.  
  906.  
  907.         --------------------------------------------------
  908.         -- Показываем ответ
  909.         --------------------------------------------------
  910.  
  911.         showDialogResponse:FireClient(
  912.             player,
  913.             response
  914.         )
  915.  
  916.  
  917.         print(
  918.             "[DIALOG SERVER] Ответ отправлен"
  919.         )
  920.  
  921.  
  922.         --------------------------------------------------
  923.         -- Через 3 секунды NPC начинает уходить
  924.         --------------------------------------------------
  925.  
  926.         task.delay(
  927.             RESPONSE_DURATION,
  928.             function()
  929.  
  930.                 makeNpcLeave()
  931.  
  932.             end
  933.         )
  934.  
  935.     end
  936. )
  937.  
  938.  
  939. --------------------------------------------------
  940. -- Очистка
  941. --------------------------------------------------
  942.  
  943. Players.PlayerRemoving:Connect(
  944.     function(player)
  945.  
  946.         playerNames[player.UserId] = nil
  947.  
  948.     end
  949. )
Advertisement
Add Comment
Please, Sign In to add comment