Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local Players = game:GetService("Players")
- local ReplicatedStorage = game:GetService("ReplicatedStorage")
- local TextService = game:GetService("TextService")
- local PathfindingService = game:GetService("PathfindingService")
- local PhysicsService = game:GetService("PhysicsService")
- --------------------------------------------------
- -- RemoteEvents
- --------------------------------------------------
- local submitPlayerName =
- ReplicatedStorage:WaitForChild("SubmitPlayerName")
- local showDialogResponse =
- ReplicatedStorage:WaitForChild("ShowDialogResponse")
- --------------------------------------------------
- -- NPC
- --------------------------------------------------
- local npc =
- workspace:WaitForChild("NPC")
- local humanoid =
- npc:WaitForChild("Humanoid")
- local rootPart =
- npc:WaitForChild("HumanoidRootPart")
- --------------------------------------------------
- -- NPC PATH
- --------------------------------------------------
- local npcPath =
- workspace:WaitForChild("NPCPath")
- local startPoint =
- npcPath:WaitForChild("Start")
- local middlePoint =
- npcPath:WaitForChild("Middle")
- local doorPoint =
- npcPath:WaitForChild("Door")
- local cornerPoint =
- npcPath:WaitForChild("Corner")
- --------------------------------------------------
- -- SETTINGS
- --------------------------------------------------
- local RESPONSE_DURATION = 3
- local WALK_SPEED = 8
- local AGENT_RADIUS = 2
- local AGENT_HEIGHT = 5
- local MAX_REPATH_ATTEMPTS = 5
- --------------------------------------------------
- -- STATE
- --------------------------------------------------
- local playerNames = {}
- local npcLeaving = false
- local npcGone = false
- --------------------------------------------------
- -- HUMANOID SETTINGS
- --------------------------------------------------
- humanoid.WalkSpeed = WALK_SPEED
- humanoid.AutoRotate = true
- humanoid.AutoJumpEnabled = false
- --------------------------------------------------
- -- ANIMATION
- --
- -- Используем уже существующую:
- --
- -- NPC
- -- └── Animate
- -- └── walk
- -- └── WalkAnim
- --------------------------------------------------
- local animateScript =
- npc:WaitForChild("Animate")
- local walkFolder =
- animateScript:WaitForChild("walk")
- local walkAnimation =
- walkFolder:WaitForChild("WalkAnim")
- print("[NPC] Найдена стандартная WalkAnim:")
- print("[NPC]", walkAnimation.AnimationId)
- --------------------------------------------------
- -- Animator
- --------------------------------------------------
- local animator =
- humanoid:FindFirstChildOfClass("Animator")
- if not animator then
- animator = Instance.new("Animator")
- animator.Parent = humanoid
- end
- --------------------------------------------------
- -- Загружаем существующую R6 walk-анимацию
- --------------------------------------------------
- local walkTrack
- local animationSuccess, animationError =
- pcall(function()
- walkTrack =
- animator:LoadAnimation(
- walkAnimation
- )
- end)
- if not animationSuccess then
- warn(
- "[NPC] Не удалось загрузить WalkAnim:",
- animationError
- )
- else
- walkTrack.Looped = true
- walkTrack.Priority =
- Enum.AnimationPriority.Movement
- print("[NPC] WalkAnim успешно загружена")
- end
- --------------------------------------------------
- -- Запуск ходьбы
- --------------------------------------------------
- local function startWalkingAnimation()
- if not walkTrack then
- return
- end
- if not walkTrack.IsPlaying then
- walkTrack:Play(
- 0.15,
- 1,
- 1
- )
- end
- end
- --------------------------------------------------
- -- Остановка ходьбы
- --------------------------------------------------
- local function stopWalkingAnimation()
- if not walkTrack then
- return
- end
- if walkTrack.IsPlaying then
- walkTrack:Stop(0.15)
- end
- end
- --------------------------------------------------
- -- СОЗДАЁМ COLLISION GROUP
- --
- -- NPC не сталкивается с игроками.
- --------------------------------------------------
- local NPC_GROUP = "NPC"
- local successCollisionGroup =
- pcall(function()
- PhysicsService:RegisterCollisionGroup(
- NPC_GROUP
- )
- end)
- --------------------------------------------------
- -- NPC НЕ СТОЛКАИВАЕТСЯ С PLAYER
- --------------------------------------------------
- pcall(function()
- PhysicsService:CollisionGroupSetCollidable(
- NPC_GROUP,
- "Default",
- true
- )
- end)
- --------------------------------------------------
- -- Определяем collision group для частей NPC
- --------------------------------------------------
- for _, object in ipairs(npc:GetDescendants()) do
- if object:IsA("BasePart") then
- object.CollisionGroup = NPC_GROUP
- end
- end
- --------------------------------------------------
- -- Игроки тоже не сталкиваются с NPC
- --------------------------------------------------
- local function setupPlayerCollision(character)
- for _, object in ipairs(character:GetDescendants()) do
- if object:IsA("BasePart") then
- PhysicsService:CollisionGroupSetCollidable(
- NPC_GROUP,
- object.CollisionGroup,
- false
- )
- end
- end
- end
- --------------------------------------------------
- -- PATHFINDING
- --------------------------------------------------
- local function createPath()
- return PathfindingService:CreatePath({
- AgentRadius = AGENT_RADIUS,
- AgentHeight = AGENT_HEIGHT,
- AgentCanJump = false,
- AgentCanClimb = false,
- })
- end
- --------------------------------------------------
- -- Движение по вычисленному пути
- --------------------------------------------------
- local function followPathTo(targetPosition)
- if npcGone then
- return false
- end
- --------------------------------------------------
- -- Создаём путь
- --------------------------------------------------
- local path =
- createPath()
- local success =
- pcall(function()
- path:ComputeAsync(
- rootPart.Position,
- targetPosition
- )
- end)
- if not success then
- warn(
- "[NPC] Ошибка ComputeAsync"
- )
- return false
- end
- --------------------------------------------------
- -- Проверяем путь
- --------------------------------------------------
- if path.Status ~= Enum.PathStatus.Success then
- warn(
- "[NPC] Pathfinding не нашёл путь к точке"
- )
- return false
- end
- local waypoints =
- path:GetWaypoints()
- print(
- "[NPC] Найдено waypoint:",
- #waypoints
- )
- --------------------------------------------------
- -- Индекс текущего waypoint
- --------------------------------------------------
- local currentWaypointIndex = 1
- --------------------------------------------------
- -- Обрабатываем блокировку пути
- --------------------------------------------------
- local pathBlocked = false
- local blockedConnection
- blockedConnection =
- path.Blocked:Connect(
- function(blockedWaypointIndex)
- if blockedWaypointIndex >=
- currentWaypointIndex then
- pathBlocked = true
- end
- end
- )
- --------------------------------------------------
- -- Начинаем ходьбу
- --------------------------------------------------
- startWalkingAnimation()
- --------------------------------------------------
- -- Идём по waypoint
- --------------------------------------------------
- while currentWaypointIndex <= #waypoints do
- if npcGone then
- break
- end
- --------------------------------------------------
- -- Если путь заблокирован
- --------------------------------------------------
- if pathBlocked then
- print(
- "[NPC] Путь заблокирован, пересчитываю"
- )
- blockedConnection:Disconnect()
- return false
- end
- local waypoint =
- waypoints[currentWaypointIndex]
- --------------------------------------------------
- -- Waypoint может требовать прыжок
- --------------------------------------------------
- if waypoint.Action ==
- Enum.PathWaypointAction.Jump then
- humanoid.Jump = true
- end
- --------------------------------------------------
- -- Двигаемся к waypoint
- --------------------------------------------------
- humanoid:MoveTo(
- waypoint.Position
- )
- local reached =
- humanoid.MoveToFinished:Wait()
- if not reached then
- print(
- "[NPC] Waypoint не достигнут"
- )
- blockedConnection:Disconnect()
- return false
- end
- currentWaypointIndex += 1
- end
- --------------------------------------------------
- -- Отключаем обработчик
- --------------------------------------------------
- if blockedConnection then
- blockedConnection:Disconnect()
- end
- return true
- end
- --------------------------------------------------
- -- Идём к конкретной контрольной точке
- --------------------------------------------------
- local function moveToPoint(point)
- if npcGone then
- return false
- end
- print(
- "========================================"
- )
- print(
- "[NPC] ИДУ К:",
- point.Name
- )
- --------------------------------------------------
- -- Несколько попыток
- --------------------------------------------------
- for attempt = 1, MAX_REPATH_ATTEMPTS do
- if npcGone then
- return false
- end
- print(
- "[NPC] Попытка:",
- attempt,
- "/",
- MAX_REPATH_ATTEMPTS
- )
- local success =
- followPathTo(
- point.Position
- )
- if success then
- print(
- "[NPC] Достиг:",
- point.Name
- )
- return true
- end
- --------------------------------------------------
- -- Небольшая пауза перед пересчётом
- --------------------------------------------------
- task.wait(0.2)
- end
- warn(
- "[NPC] Не удалось достичь:",
- point.Name
- )
- return false
- end
- --------------------------------------------------
- -- УХОД NPC
- --------------------------------------------------
- local function makeNpcLeave()
- if npcLeaving then
- return
- end
- if npcGone then
- return
- end
- npcLeaving = true
- print("========================================")
- print("[NPC] НАЧИНАЮ УХОД")
- print("========================================")
- --------------------------------------------------
- -- Start
- --------------------------------------------------
- local reachedStart =
- moveToPoint(startPoint)
- if not reachedStart then
- warn(
- "[NPC] Start не достигнут"
- )
- end
- --------------------------------------------------
- -- Middle
- --------------------------------------------------
- local reachedMiddle =
- moveToPoint(middlePoint)
- if not reachedMiddle then
- warn(
- "[NPC] Middle не достигнут"
- )
- end
- --------------------------------------------------
- -- Door
- --------------------------------------------------
- local reachedDoor =
- moveToPoint(doorPoint)
- if not reachedDoor then
- warn(
- "[NPC] Door не достигнут"
- )
- end
- --------------------------------------------------
- -- Corner
- --------------------------------------------------
- local reachedCorner =
- moveToPoint(cornerPoint)
- if not reachedCorner then
- warn(
- "[NPC] Corner не достигнут"
- )
- end
- --------------------------------------------------
- -- Останавливаем анимацию
- --------------------------------------------------
- stopWalkingAnimation()
- --------------------------------------------------
- -- NPC исчезает
- --------------------------------------------------
- if npc.Parent then
- print(
- "[NPC] Достиг Corner"
- )
- print(
- "[NPC] NPC исчезает"
- )
- npcGone = true
- npc:Destroy()
- end
- end
- --------------------------------------------------
- -- ПОЛУЧЕНИЕ ИМЕНИ
- --------------------------------------------------
- submitPlayerName.OnServerEvent:Connect(
- function(player, rawName)
- print("========================================")
- print("[DIALOG SERVER] Получено имя")
- print("[DIALOG SERVER] Игрок:", player.Name)
- print("[DIALOG SERVER] UserId:", player.UserId)
- print("[DIALOG SERVER] Имя:", rawName)
- print("========================================")
- --------------------------------------------------
- -- NPC уже уходит
- --------------------------------------------------
- if npcLeaving or npcGone then
- warn(
- "[DIALOG SERVER] NPC уже уходит"
- )
- return
- end
- --------------------------------------------------
- -- Проверяем тип
- --------------------------------------------------
- if typeof(rawName) ~= "string" then
- warn(
- "[DIALOG SERVER] Имя не строка"
- )
- return
- end
- --------------------------------------------------
- -- Убираем пробелы
- --------------------------------------------------
- rawName =
- rawName:match("^%s*(.-)%s*$")
- --------------------------------------------------
- -- Проверяем пустоту
- --------------------------------------------------
- if rawName == "" then
- warn(
- "[DIALOG SERVER] Игрок отправил пустое имя"
- )
- return
- end
- --------------------------------------------------
- -- Максимум 20 символов
- --------------------------------------------------
- local length =
- utf8.len(rawName)
- if not length then
- warn(
- "[DIALOG SERVER] Некорректный UTF-8"
- )
- return
- end
- if length > 20 then
- local cutPosition =
- utf8.offset(rawName, 21)
- if cutPosition then
- rawName =
- string.sub(
- rawName,
- 1,
- cutPosition - 1
- )
- end
- end
- --------------------------------------------------
- -- Фильтрация
- --------------------------------------------------
- print(
- "[DIALOG SERVER] Фильтруем имя..."
- )
- local success, filterResult =
- pcall(function()
- return TextService:FilterStringAsync(
- rawName,
- player.UserId
- )
- end)
- if not success then
- warn(
- "[DIALOG SERVER] FilterStringAsync:",
- filterResult
- )
- return
- end
- --------------------------------------------------
- -- Получаем безопасный текст
- --------------------------------------------------
- local successFiltered, filteredName =
- pcall(function()
- return filterResult:GetNonChatStringForUserAsync(
- player.UserId
- )
- end)
- if not successFiltered then
- warn(
- "[DIALOG SERVER] Ошибка фильтрации:",
- filteredName
- )
- return
- end
- --------------------------------------------------
- -- Проверяем результат
- --------------------------------------------------
- if typeof(filteredName) ~= "string" then
- warn(
- "[DIALOG SERVER] filteredName не строка"
- )
- return
- end
- if filteredName == "" then
- warn(
- "[DIALOG SERVER] После фильтрации имя пустое"
- )
- return
- end
- --------------------------------------------------
- -- Сохраняем имя
- --------------------------------------------------
- playerNames[player.UserId] =
- filteredName
- print(
- "[DIALOG SERVER] Имя сохранено:",
- filteredName
- )
- --------------------------------------------------
- -- Формируем ответ
- --------------------------------------------------
- local response =
- "Понятно, " .. filteredName .. "."
- print(
- "[DIALOG SERVER] Отправляем:",
- response
- )
- --------------------------------------------------
- -- Показываем ответ
- --------------------------------------------------
- showDialogResponse:FireClient(
- player,
- response
- )
- print(
- "[DIALOG SERVER] Ответ отправлен"
- )
- --------------------------------------------------
- -- Через 3 секунды NPC начинает уходить
- --------------------------------------------------
- task.delay(
- RESPONSE_DURATION,
- function()
- makeNpcLeave()
- end
- )
- end
- )
- --------------------------------------------------
- -- Очистка
- --------------------------------------------------
- Players.PlayerRemoving:Connect(
- function(player)
- playerNames[player.UserId] = nil
- end
- )
Advertisement
Add Comment
Please, Sign In to add comment