Roblox · Хоррор · урок 5

Монстры

Монстр появляется за спиной и гонится за игроком. Спасение — добежать до света.

Структура

Синим — что добавляем на этом уроке.

ServerStorage
└─ Monster (Model) — Humanoid, HumanoidRootPart, части тела
   └─ MonsterAnim (Script)
Workspace
├─ MonsterSpawn (Part) — невидимая точка позади игрока
├─ MonsterTrigger (Part)
│  └─ MonsterTrigger (Script)
└─ SafeZone (Part) — светлое место
   ├─ PointLight (PointLight)
   └─ LightTrigger (Script)

Шаги

  1. Проще всего: Avatar → Rig Builder → R15 → перекрась части в чёрный, увеличь. В методичке — свой монстр из деталей и плагин RigEdit Lite: так тоже можно, главное — внутри Humanoid и HumanoidRootPart.
  2. Назови модель «Monster», у Humanoid WalkSpeed = 20 (бег игрока — 25, шаг — 16). Скорость монстра решает, насколько страшно.
  3. Внутрь — Script «MonsterAnim»: анимация ходьбы. Для R6-монстра поменяй WALK_ID на 180426354.
  4. Монстра — в ServerStorage. На карте только точка «MonsterSpawn» (невидимая) — позади места, где сработает триггер.
  5. Триггер «MonsterTrigger» со скриптом: монстр появляется и бежит к игроку, ближе 5 studs — поймал.
  6. «SafeZone» — светлая зона с яркой PointLight и скриптом «LightTrigger»: монстр исчезает.
  7. Погоня заканчивается сама: если игрок погиб или монстра убрал свет. Потом триггер можно пройти заново.

Скрипты

MonsterAnim

Где: ServerStorage → Monster · Script
Зачем: Анимация ходьбы монстра.

-- модель монстра
local monster = script.Parent
-- Humanoid
local humanoid = monster:WaitForChild("Humanoid")
-- Animator (создаём, если нет)
local animator = humanoid:FindFirstChildOfClass("Animator") or Instance.new("Animator", humanoid)
-- стандартная ходьба R15; для R6 — 180426354
local WALK_ID = "rbxassetid://507777826"

-- анимация
local walk = Instance.new("Animation")
-- какая
walk.AnimationId = WALK_ID
-- загружаем
local track = animator:LoadAnimation(walk)
-- по кругу
track.Looped = true

-- скорость монстра изменилась
humanoid.Running:Connect(function(speed)
    -- пошёл
    if speed > 0.5 and not track.IsPlaying then
        -- шагаем
        track:Play()
    -- остановился
    elseif speed <= 0.5 and track.IsPlaying then
        -- стоим
        track:Stop()
    -- конец проверки
    end
-- конец функции
end)

MonsterTrigger

Где: Workspace → MonsterTrigger · Script
Зачем: Выпускает монстра и ведёт погоню.

-- образец монстра
local SS = game:GetService("ServerStorage")
-- игроки
local Players = game:GetService("Players")
-- зона
local trigger = script.Parent
-- где появляется монстр
local spawnPoint = workspace:WaitForChild("MonsterSpawn")
-- ближе — поймал
local KILL_DISTANCE = 5
-- монстр уже гонится
local active = false

-- погоня за игроком
local function Chase(monster, player)
    -- Humanoid монстра
    local mHumanoid = monster:WaitForChild("Humanoid")
    -- центр монстра
    local mRoot = monster:WaitForChild("HumanoidRootPart")
    -- движение считает сервер — без рывков
    mRoot:SetNetworkOwner(nil)
    -- пока монстр в игре
    while monster.Parent and mHumanoid.Health > 0 do
        -- персонаж цели
        local character = player.Character
        -- её Humanoid
        local humanoid = character and character:FindFirstChildOfClass("Humanoid")
        -- её центр
        local root = character and character:FindFirstChild("HumanoidRootPart")
        -- цель погибла или ушла — конец погони
        if not humanoid or not root or humanoid.Health <= 0 then break end
        -- бежим к игроку
        mHumanoid:MoveTo(root.Position)
        -- догнал
        if (root.Position - mRoot.Position).Magnitude <= KILL_DISTANCE then
            -- поймал
            humanoid.Health = 0
            -- конец погони
            break
        -- конец проверки
        end
        -- 10 раз в секунду
        task.wait(0.1)
    -- конец цикла
    end
    -- монстр ещё секунду-две стоит
    task.wait(2)
    -- и исчезает
    monster:Destroy()
-- конец функции
end

-- касание зоны
trigger.Touched:Connect(function(hit)
    -- монстр уже бежит
    if active then return end
    -- кто коснулся
    local player = Players:GetPlayerFromCharacter(hit.Parent)
    -- образец
    local sample = SS:FindFirstChild("Monster")
    -- не игрок или монстра нет
    if not player or not sample then return end
    -- занято
    active = true
    -- копия
    local monster = sample:Clone()
    -- на точку появления
    monster:PivotTo(spawnPoint.CFrame)
    -- в игру
    monster.Parent = workspace
    -- гонимся (ждём, пока закончится)
    Chase(monster, player)
    -- можно снова
    active = false
-- конец функции
end)

LightTrigger

Где: Workspace → SafeZone · Script
Зачем: Свет прогоняет монстра.

-- игроки
local Players = game:GetService("Players")
-- светлая зона
local trigger = script.Parent

-- касание
trigger.Touched:Connect(function(hit)
    -- только игрок
    if not Players:GetPlayerFromCharacter(hit.Parent) then return end
    -- монстр в игре?
    local monster = workspace:FindFirstChild("Monster")
    -- свет его прогоняет — погоня закончится
    if monster then monster:Destroy() end
-- конец функции
end)

Проверка

Запусти Play (или Run) и убедись:

Roblox · Horror · lesson 5

Monsters

A monster appears behind the player and chases them. The escape is to reach the light.

Structure

Blue — what we add in this lesson.

ServerStorage
└─ Monster (Model) — Humanoid, HumanoidRootPart, body parts
   └─ MonsterAnim (Script)
Workspace
├─ MonsterSpawn (Part) — an invisible point behind the player
├─ MonsterTrigger (Part)
│  └─ MonsterTrigger (Script)
└─ SafeZone (Part) — a lit place
   ├─ PointLight (PointLight)
   └─ LightTrigger (Script)

Steps

  1. The easiest way: Avatar → Rig Builder → R15 → recolor the parts black and scale it up. The workbook builds a monster from parts with the RigEdit Lite plugin: that works too, as long as there's a Humanoid and a HumanoidRootPart inside.
  2. Name the model "Monster", Humanoid WalkSpeed = 20 (the player runs at 25 and walks at 16). The monster's speed decides how scary it is.
  3. Inside put a Script "MonsterAnim": the walk animation. For an R6 monster change WALK_ID to 180426354.
  4. Put the monster in ServerStorage. On the map there's only a point "MonsterSpawn" (invisible) — behind the place where the trigger fires.
  5. A trigger "MonsterTrigger" with a script: the monster appears and runs at the player; closer than 5 studs — caught.
  6. "SafeZone" is a lit zone with a bright PointLight and a script "LightTrigger": the monster disappears.
  7. The chase ends by itself: if the player died or the light removed the monster. After that the trigger can be passed again.

Scripts

MonsterAnim

Where: ServerStorage → Monster · Script
Why: The monster's walk animation.

-- the monster model
local monster = script.Parent
-- Humanoid
local humanoid = monster:WaitForChild("Humanoid")
-- Animator (create one if missing)
local animator = humanoid:FindFirstChildOfClass("Animator") or Instance.new("Animator", humanoid)
-- the standard R15 walk; for R6 — 180426354
local WALK_ID = "rbxassetid://507777826"

-- the animation
local walk = Instance.new("Animation")
-- which one
walk.AnimationId = WALK_ID
-- load it
local track = animator:LoadAnimation(walk)
-- looped
track.Looped = true

-- the monster's speed changed
humanoid.Running:Connect(function(speed)
    -- started walking
    if speed > 0.5 and not track.IsPlaying then
        -- walk
        track:Play()
    -- stopped
    elseif speed <= 0.5 and track.IsPlaying then
        -- stand
        track:Stop()
    -- end of check
    end
-- end of function
end)

MonsterTrigger

Where: Workspace → MonsterTrigger · Script
Why: Releases the monster and runs the chase.

-- the monster template
local SS = game:GetService("ServerStorage")
-- players
local Players = game:GetService("Players")
-- the zone
local trigger = script.Parent
-- where the monster appears
local spawnPoint = workspace:WaitForChild("MonsterSpawn")
-- closer — caught
local KILL_DISTANCE = 5
-- the monster is already chasing
local active = false

-- chasing the player
local function Chase(monster, player)
    -- the monster's Humanoid
    local mHumanoid = monster:WaitForChild("Humanoid")
    -- the monster's center
    local mRoot = monster:WaitForChild("HumanoidRootPart")
    -- the server runs the movement — no jerks
    mRoot:SetNetworkOwner(nil)
    -- while the monster is in the game
    while monster.Parent and mHumanoid.Health > 0 do
        -- the target's character
        local character = player.Character
        -- its Humanoid
        local humanoid = character and character:FindFirstChildOfClass("Humanoid")
        -- its center
        local root = character and character:FindFirstChild("HumanoidRootPart")
        -- the target died or left — the chase ends
        if not humanoid or not root or humanoid.Health <= 0 then break end
        -- run to the player
        mHumanoid:MoveTo(root.Position)
        -- caught up
        if (root.Position - mRoot.Position).Magnitude <= KILL_DISTANCE then
            -- caught
            humanoid.Health = 0
            -- end of the chase
            break
        -- end of check
        end
        -- 10 times a second
        task.wait(0.1)
    -- end of loop
    end
    -- the monster stands for another second or two
    task.wait(2)
    -- and disappears
    monster:Destroy()
-- end of function
end

-- the zone was touched
trigger.Touched:Connect(function(hit)
    -- the monster is already running
    if active then return end
    -- who touched it
    local player = Players:GetPlayerFromCharacter(hit.Parent)
    -- the template
    local sample = SS:FindFirstChild("Monster")
    -- not a player or no monster
    if not player or not sample then return end
    -- busy
    active = true
    -- a copy
    local monster = sample:Clone()
    -- onto the spawn point
    monster:PivotTo(spawnPoint.CFrame)
    -- into the game
    monster.Parent = workspace
    -- chase (wait until it ends)
    Chase(monster, player)
    -- can fire again
    active = false
-- end of function
end)

LightTrigger

Where: Workspace → SafeZone · Script
Why: Light drives the monster away.

-- players
local Players = game:GetService("Players")
-- the lit zone
local trigger = script.Parent

-- touch
trigger.Touched:Connect(function(hit)
    -- players only
    if not Players:GetPlayerFromCharacter(hit.Parent) then return end
    -- is the monster in the game?
    local monster = workspace:FindFirstChild("Monster")
    -- the light drives it away — the chase will end
    if monster then monster:Destroy() end
-- end of function
end)

Testing

Press Play (or Run) and make sure: