Roblox · Приключение · урок 2
Житель даёт задание, на экране видно, что сделать и сколько осталось. Первый квест — собрать мешки с песком.
Синим — что добавляем на этом уроке.
ReplicatedStorage └─ Events (Folder) └─ CompleteEvent, CancelEvent (RemoteEvent) ServerScriptService └─ QuestSystem (Script) Workspace ├─ Elder (Model) │ ├─ Head (MeshPart) │ │ └─ ProximityPrompt (ProximityPrompt) — «Взять задание» │ └─ QuestGiver (Script) │ ├─ Title, Description (StringValue) │ └─ Objective, Reward (IntValue) — 5 и 20 └─ Sandbags (Folder) └─ Sandbag (Part) ├─ ProximityPrompt (ProximityPrompt) └─ QuestItem (Script) StarterGui └─ QuestGui (ScreenGui) — ResetOnSpawn выкл. ├─ QuestFrame (Frame) — Title, Description, Progress, CancelButton ├─ DoneLabel (TextLabel) — Visible выкл. └─ QuestLocal (LocalScript)
Где: ServerScriptService · Script
Зачем: Монеты, квест игрока, награда, отмена.
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- папка событий
local events = RS:WaitForChild("Events")
-- квест выполнен — сообщить игроку
local completeEvent = events:WaitForChild("CompleteEvent")
-- игрок отменил квест
local cancelEvent = events:WaitForChild("CancelEvent")
-- создаёт контейнер со значением
local function Value(parent, class, name, value)
-- контейнер
local v = Instance.new(class)
-- имя
v.Name = name
-- значение
v.Value = value
-- на место
v.Parent = parent
-- отдаём
return v
-- конец функции
end
-- у игрока нет квеста
local function ClearQuest(quest)
-- сначала цель: теперь сброс прогресса ничего не засчитает
quest.Objective.Value = 0
-- прогресс
quest.Progress.Value = 0
-- название пустое = квеста нет
quest.Title.Value = ""
-- описание
quest.Description.Value = ""
-- награда
quest.Reward.Value = 0
-- конец функции
end
-- игрок зашёл
Players.PlayerAdded:Connect(function(player)
-- таблица по Tab
local leaderstats = Instance.new("Folder")
-- имя строго такое
leaderstats.Name = "leaderstats"
-- в игрока
leaderstats.Parent = player
-- монеты
local coins = Value(leaderstats, "IntValue", "Coins", 0)
-- текущий квест игрока
local quest = Instance.new("Folder")
-- имя
quest.Name = "QuestInfo"
-- в игрока — клиент тоже видит
quest.Parent = player
-- название
Value(quest, "StringValue", "Title", "")
-- что сделать
Value(quest, "StringValue", "Description", "")
-- сколько нужно
Value(quest, "IntValue", "Objective", 0)
-- сколько уже
local progress = Value(quest, "IntValue", "Progress", 0)
-- награда в монетах
Value(quest, "IntValue", "Reward", 0)
-- прогресс изменился
progress.Changed:Connect(function(value)
-- цель
local objective = quest.Objective.Value
-- квеста нет или ещё не всё
if objective <= 0 or value < objective then return end
-- запоминаем награду
local reward = quest.Reward.Value
-- и название
local title = quest.Title.Value
-- квест закрыт — второй раз награда не выдастся
ClearQuest(quest)
-- награда
coins.Value += reward
-- сообщение на экране
completeEvent:FireClient(player, title, reward)
-- конец функции
end)
-- конец функции
end)
-- кнопка «Отменить»
cancelEvent.OnServerEvent:Connect(function(player)
-- квест игрока
local quest = player:FindFirstChild("QuestInfo")
-- очищаем
if quest then ClearQuest(quest) end
-- конец функции
end)Где: Workspace → Elder · Script
Зачем: Выдаёт квест.
-- персонаж, который даёт квест
local npc = script.Parent
-- «Взять задание»
local prompt = npc:WaitForChild("Head"):WaitForChild("ProximityPrompt")
-- игрок нажал E
prompt.Triggered:Connect(function(player)
-- квест игрока
local quest = player:FindFirstChild("QuestInfo")
-- уже есть другой квест
if not quest or quest.Title.Value ~= "" then return end
-- название — из значений под скриптом
quest.Title.Value = script.Title.Value
-- описание
quest.Description.Value = script.Description.Value
-- награда
quest.Reward.Value = script.Reward.Value
-- с нуля
quest.Progress.Value = 0
-- цель — последней: квест начался
quest.Objective.Value = script.Objective.Value
-- конец функции
end)Где: Workspace → Sandbags → Sandbag · Script
Зачем: Предмет для квеста.
-- мешок с песком
local item = script.Parent
-- «Взять»
local prompt = item:WaitForChild("ProximityPrompt")
-- для какого квеста — как Title у квестодателя
local QUEST = "Мешки с песком"
-- через сколько секунд мешок вернётся
local RESPAWN = 60
-- игрок нажал E
prompt.Triggered:Connect(function(player)
-- квест игрока
local quest = player:FindFirstChild("QuestInfo")
-- мешки нужны только с этим квестом
if not quest or quest.Title.Value ~= QUEST then return end
-- +1 к прогрессу
quest.Progress.Value += 1
-- второй раз не взять
prompt.Enabled = false
-- мешок пропал
item.Transparency = 1
-- и не мешает
item.CanCollide = false
-- ждём
task.wait(RESPAWN)
-- вернулся
item.Transparency = 0
-- снова твёрдый
item.CanCollide = true
-- можно взять
prompt.Enabled = true
-- конец функции
end)Где: StarterGui → QuestGui · LocalScript
Зачем: Окно квеста.
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- этот игрок
local player = Players.LocalPlayer
-- его квест
local quest = player:WaitForChild("QuestInfo")
-- события
local events = RS:WaitForChild("Events")
-- квест выполнен
local completeEvent = events:WaitForChild("CompleteEvent")
-- отмена
local cancelEvent = events:WaitForChild("CancelEvent")
-- QuestGui
local gui = script.Parent
-- окно квеста
local frame = gui:WaitForChild("QuestFrame")
-- надпись «Выполнено»
local doneLabel = gui:WaitForChild("DoneLabel")
-- обновить окно
local function Update()
-- квест есть — окно видно
frame.Visible = quest.Title.Value ~= ""
-- название
frame.Title.Text = quest.Title.Value
-- описание
frame.Description.Text = quest.Description.Value
-- прогресс: 2 / 5
frame.Progress.Text = quest.Progress.Value .. " / " .. quest.Objective.Value
-- конец функции
end
-- все значения квеста
for _, value in ipairs(quest:GetChildren()) do
-- изменилось — обновляем
value.Changed:Connect(Update)
-- конец перебора
end
-- сразу при входе
Update()
-- «Отменить»
frame.CancelButton.MouseButton1Click:Connect(function()
-- просим сервер
cancelEvent:FireServer()
-- конец функции
end)
-- квест выполнен
completeEvent.OnClientEvent:Connect(function(title, reward)
-- текст
doneLabel.Text = "Квест «" .. title .. "» выполнен! +" .. reward .. " монет"
-- показываем
doneLabel.Visible = true
-- 3 секунды
task.wait(3)
-- прячем
doneLabel.Visible = false
-- конец функции
end)Запусти Play (или Run) и убедись:
Roblox · Adventure · lesson 2
A villager gives a quest, and the screen shows what to do and how much is left. The first quest is to collect sandbags.
Blue — what we add in this lesson.
ReplicatedStorage └─ Events (Folder) └─ CompleteEvent, CancelEvent (RemoteEvent) ServerScriptService └─ QuestSystem (Script) Workspace ├─ Elder (Model) │ ├─ Head (MeshPart) │ │ └─ ProximityPrompt (ProximityPrompt) — "Взять задание" (take quest) │ └─ QuestGiver (Script) │ ├─ Title, Description (StringValue) │ └─ Objective, Reward (IntValue) — 5 and 20 └─ Sandbags (Folder) └─ Sandbag (Part) ├─ ProximityPrompt (ProximityPrompt) └─ QuestItem (Script) StarterGui └─ QuestGui (ScreenGui) — ResetOnSpawn off ├─ QuestFrame (Frame) — Title, Description, Progress, CancelButton ├─ DoneLabel (TextLabel) — Visible off └─ QuestLocal (LocalScript)
Where: ServerScriptService · Script
Why: Coins, the player's quest, the reward, cancelling.
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- the events folder
local events = RS:WaitForChild("Events")
-- quest done — tell the player
local completeEvent = events:WaitForChild("CompleteEvent")
-- the player cancelled the quest
local cancelEvent = events:WaitForChild("CancelEvent")
-- creates a value container
local function Value(parent, class, name, value)
-- the container
local v = Instance.new(class)
-- name
v.Name = name
-- the value
v.Value = value
-- into place
v.Parent = parent
-- return it
return v
-- end of function
end
-- the player has no quest
local function ClearQuest(quest)
-- objective first: now resetting the progress won't count anything
quest.Objective.Value = 0
-- progress
quest.Progress.Value = 0
-- empty name = no quest
quest.Title.Value = ""
-- description
quest.Description.Value = ""
-- reward
quest.Reward.Value = 0
-- end of function
end
-- a player joined
Players.PlayerAdded:Connect(function(player)
-- the Tab board
local leaderstats = Instance.new("Folder")
-- the name must be exactly this
leaderstats.Name = "leaderstats"
-- into the player
leaderstats.Parent = player
-- coins
local coins = Value(leaderstats, "IntValue", "Coins", 0)
-- the player's current quest
local quest = Instance.new("Folder")
-- name
quest.Name = "QuestInfo"
-- into the player — the client sees it too
quest.Parent = player
-- name
Value(quest, "StringValue", "Title", "")
-- what to do
Value(quest, "StringValue", "Description", "")
-- how many are needed
Value(quest, "IntValue", "Objective", 0)
-- how many so far
local progress = Value(quest, "IntValue", "Progress", 0)
-- the reward in coins
Value(quest, "IntValue", "Reward", 0)
-- the progress changed
progress.Changed:Connect(function(value)
-- the objective
local objective = quest.Objective.Value
-- no quest or not done yet
if objective <= 0 or value < objective then return end
-- remember the reward
local reward = quest.Reward.Value
-- and the name
local title = quest.Title.Value
-- the quest is closed — the reward won't be given twice
ClearQuest(quest)
-- reward
coins.Value += reward
-- an on-screen message
completeEvent:FireClient(player, title, reward)
-- end of function
end)
-- end of function
end)
-- the Cancel button
cancelEvent.OnServerEvent:Connect(function(player)
-- the player's quest
local quest = player:FindFirstChild("QuestInfo")
-- clear it
if quest then ClearQuest(quest) end
-- end of function
end)Where: Workspace → Elder · Script
Why: Gives a quest.
-- the character who gives the quest
local npc = script.Parent
-- "Взять задание" (take quest)
local prompt = npc:WaitForChild("Head"):WaitForChild("ProximityPrompt")
-- the player pressed E
prompt.Triggered:Connect(function(player)
-- the player's quest
local quest = player:FindFirstChild("QuestInfo")
-- already has another quest
if not quest or quest.Title.Value ~= "" then return end
-- the name — from the values under the script
quest.Title.Value = script.Title.Value
-- description
quest.Description.Value = script.Description.Value
-- reward
quest.Reward.Value = script.Reward.Value
-- from zero
quest.Progress.Value = 0
-- the objective last: the quest has started
quest.Objective.Value = script.Objective.Value
-- end of function
end)Where: Workspace → Sandbags → Sandbag · Script
Why: A quest item.
-- a sandbag
local item = script.Parent
-- "Взять" (take)
local prompt = item:WaitForChild("ProximityPrompt")
-- which quest it's for — the same as the quest giver's Title
local QUEST = "Мешки с песком"
-- how many seconds until the bag comes back
local RESPAWN = 60
-- the player pressed E
prompt.Triggered:Connect(function(player)
-- the player's quest
local quest = player:FindFirstChild("QuestInfo")
-- bags are only needed with this quest
if not quest or quest.Title.Value ~= QUEST then return end
-- +1 progress
quest.Progress.Value += 1
-- can't be taken twice
prompt.Enabled = false
-- the bag is gone
item.Transparency = 1
-- and doesn't get in the way
item.CanCollide = false
-- wait
task.wait(RESPAWN)
-- came back
item.Transparency = 0
-- solid again
item.CanCollide = true
-- can be taken
prompt.Enabled = true
-- end of function
end)Where: StarterGui → QuestGui · LocalScript
Why: The quest window.
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- this player
local player = Players.LocalPlayer
-- their quest
local quest = player:WaitForChild("QuestInfo")
-- events
local events = RS:WaitForChild("Events")
-- quest complete
local completeEvent = events:WaitForChild("CompleteEvent")
-- cancel
local cancelEvent = events:WaitForChild("CancelEvent")
-- QuestGui
local gui = script.Parent
-- the quest window
local frame = gui:WaitForChild("QuestFrame")
-- the "Done" label
local doneLabel = gui:WaitForChild("DoneLabel")
-- update the window
local function Update()
-- there's a quest — the window is visible
frame.Visible = quest.Title.Value ~= ""
-- name
frame.Title.Text = quest.Title.Value
-- description
frame.Description.Text = quest.Description.Value
-- progress: 2 / 5
frame.Progress.Text = quest.Progress.Value .. " / " .. quest.Objective.Value
-- end of function
end
-- all quest values
for _, value in ipairs(quest:GetChildren()) do
-- changed — update
value.Changed:Connect(Update)
-- end of loop
end
-- right on joining
Update()
-- Cancel
frame.CancelButton.MouseButton1Click:Connect(function()
-- ask the server
cancelEvent:FireServer()
-- end of function
end)
-- quest complete
completeEvent.OnClientEvent:Connect(function(title, reward)
-- text
doneLabel.Text = "Квест «" .. title .. "» выполнен! +" .. reward .. " монет"
-- show it
doneLabel.Visible = true
-- 3 seconds
task.wait(3)
-- hide
doneLabel.Visible = false
-- end of function
end)Press Play (or Run) and make sure: