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")
- --------------------------------------------------
- -- 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")
- --------------------------------------------------
- -- WALK ANIMATION
- --------------------------------------------------
- local walkAnimation =
- npc:WaitForChild("WalkAnimation")
- --------------------------------------------------
- -- Имена игроков
- --
- -- UserId -> имя персонажа
- --------------------------------------------------
- local playerNames = {}
- --------------------------------------------------
- -- Состояние NPC
- --------------------------------------------------
- local npcLeaving = false
- local npcGone = false
- --------------------------------------------------
- -- Настройки
- --------------------------------------------------
- local RESPONSE_DURATION = 3
- local WALK_SPEED = 8
- --------------------------------------------------
- -- Настройка Humanoid
- --------------------------------------------------
- humanoid.WalkSpeed = WALK_SPEED
- humanoid.AutoRotate = true
- humanoid.AutoJumpEnabled = false
- --------------------------------------------------
- -- Animator
- --------------------------------------------------
- local animator =
- humanoid:FindFirstChildOfClass("Animator")
- if not animator then
- animator = Instance.new("Animator")
- animator.Parent = humanoid
- end
- --------------------------------------------------
- -- Загружаем ходьбу
- --------------------------------------------------
- local walkTrack
- local animationSuccess, animationResult =
- pcall(function()
- return animator:LoadAnimation(
- walkAnimation
- )
- end)
- if animationSuccess then
- walkTrack = animationResult
- walkTrack.Looped = true
- walkTrack.Priority =
- Enum.AnimationPriority.Movement
- print("[NPC] Анимация ходьбы загружена")
- else
- warn(
- "[NPC] Не удалось загрузить WalkAnimation:",
- animationResult
- )
- end
- --------------------------------------------------
- -- Функция запуска ходьбы
- --------------------------------------------------
- local function startWalkingAnimation()
- if not walkTrack then
- return
- end
- if not walkTrack.IsPlaying then
- walkTrack:Play(
- 0.2,
- 1,
- 1
- )
- end
- end
- --------------------------------------------------
- -- Функция остановки ходьбы
- --------------------------------------------------
- local function stopWalkingAnimation()
- if not walkTrack then
- return
- end
- if walkTrack.IsPlaying then
- walkTrack:Stop(0.2)
- end
- end
- --------------------------------------------------
- -- Перемещение к точке
- --------------------------------------------------
- local function moveToPoint(point)
- if npcGone then
- return false
- end
- print(
- "[NPC] Иду к точке:",
- point.Name
- )
- --------------------------------------------------
- -- Сохраняем текущую высоту NPC
- --------------------------------------------------
- local targetPosition = Vector3.new(
- point.Position.X,
- rootPart.Position.Y,
- point.Position.Z
- )
- --------------------------------------------------
- -- Запускаем анимацию
- --------------------------------------------------
- startWalkingAnimation()
- --------------------------------------------------
- -- Функция повторного MoveTo
- --
- -- Это предотвращает 8-секундный таймаут.
- --------------------------------------------------
- local reached = false
- local finished = false
- local connection
- connection =
- humanoid.MoveToFinished:Connect(function(success)
- reached = success
- finished = true
- end)
- humanoid:MoveTo(targetPosition)
- --------------------------------------------------
- -- Обновляем MoveTo каждые несколько секунд
- --------------------------------------------------
- local startTime = os.clock()
- while not finished do
- if npcGone then
- break
- end
- -- Если NPC почему-то перестал идти,
- -- снова задаём точку.
- if os.clock() - startTime >= 5 then
- humanoid:MoveTo(targetPosition)
- startTime = os.clock()
- end
- task.wait(0.1)
- end
- if connection then
- connection:Disconnect()
- end
- --------------------------------------------------
- -- Если достигли точки
- --------------------------------------------------
- if reached then
- print(
- "[NPC] Достиг точки:",
- point.Name
- )
- else
- warn(
- "[NPC] Не смог достичь точки:",
- point.Name
- )
- end
- return reached
- end
- --------------------------------------------------
- -- Уход NPC
- --------------------------------------------------
- local function makeNpcLeave()
- if npcLeaving then
- return
- end
- if npcGone then
- return
- end
- npcLeaving = true
- print("========================================")
- print("[NPC] НАЧИНАЮ УХОД")
- print("========================================")
- --------------------------------------------------
- -- Останавливаем возможное движение
- --------------------------------------------------
- humanoid:MoveTo(
- Vector3.new(
- rootPart.Position.X,
- rootPart.Position.Y,
- rootPart.Position.Z
- )
- )
- --------------------------------------------------
- -- Сначала идём к Start
- --------------------------------------------------
- local startReached =
- moveToPoint(startPoint)
- if not startReached then
- warn(
- "[NPC] Не удалось дойти до Start"
- )
- end
- --------------------------------------------------
- -- Затем в середину комнаты
- --------------------------------------------------
- local middleReached =
- moveToPoint(middlePoint)
- if not middleReached then
- warn(
- "[NPC] Не удалось дойти до Middle"
- )
- end
- --------------------------------------------------
- -- Затем за дверь
- --------------------------------------------------
- local doorReached =
- moveToPoint(doorPoint)
- if not doorReached then
- warn(
- "[NPC] Не удалось дойти до Door"
- )
- end
- --------------------------------------------------
- -- Затем за угол
- --------------------------------------------------
- local cornerReached =
- moveToPoint(cornerPoint)
- if not cornerReached then
- warn(
- "[NPC] Не удалось дойти до Corner"
- )
- end
- --------------------------------------------------
- -- Останавливаем анимацию
- --------------------------------------------------
- stopWalkingAnimation()
- --------------------------------------------------
- -- NPC исчезает
- --------------------------------------------------
- if npc.Parent then
- 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
- --------------------------------------------------
- -- Ограничение длины
- --------------------------------------------------
- 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] Имя сохранено:",
- playerNames[player.UserId]
- )
- --------------------------------------------------
- -- Формируем ответ
- --------------------------------------------------
- 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