Roblox · Захват флага · урок 2

Команды

Окно выбора команды: игрок жмёт «Синие» или «Красные», попадает в команду и переносится на её половину лобби.

Структура

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

Teams
├─ Синие (Team) — TeamColor Really blue, AutoAssignable выкл.
└─ Красные (Team) — TeamColor Really red, AutoAssignable выкл.
Workspace
├─ Lobby (Model)
│  └─ Neutral (SpawnLocation) — Neutral вкл. — до выбора команды
├─ LobbySpawn (Folder)
│  └─ Синие, Красные (SpawnLocation) — Neutral выкл., TeamColor команды
└─ GameSpawn (Folder) — на поле
   └─ Синие, Красные (SpawnLocation) — Neutral выкл., TeamColor команды
ReplicatedStorage
├─ TeamEvent (RemoteEvent)
└─ Lobby (BoolValue) — Value вкл.
ServerScriptService
└─ TeamsServer (Script)
StarterGui
└─ TeamGui (ScreenGui) — ResetOnSpawn выкл.
   ├─ Frame (Frame)
   │  └─ Синие, Красные (TextButton) — имя кнопки = имя команды
   └─ TeamsLocal (LocalScript)

Шаги

  1. Model → Service → Teams (если сервиса нет в Explorer). В Teams — две Team: «Синие» (TeamColor Really blue) и «Красные» (Really red). AutoAssignable выкл. — команду выбирает игрок.
  2. В лобби — SpawnLocation «Neutral» (Neutral вкл.): здесь появляются, пока команда не выбрана.
  3. Workspace → Folder «LobbySpawn»: две SpawnLocation на половинах лобби — «Синие» и «Красные», Neutral выкл., TeamColor как у команды. Такая же папка «GameSpawn» — точки на поле.
  4. ReplicatedStorage → RemoteEvent «TeamEvent» и BoolValue «Lobby» (Value вкл. — пригодится для таймера).
  5. StarterGui → ScreenGui «TeamGui» (ResetOnSpawn выкл. — иначе окно появится снова после возрождения). Внутри Frame, в нём две TextButton, названные ровно как команды: «Синие» и «Красные».
  6. LocalScript «TeamsLocal» в TeamGui, Script «TeamsServer» в ServerScriptService.
  7. Сервер проверяет, что такая команда есть: клиент может прислать что угодно.

Скрипты

TeamsLocal

Где: StarterGui → TeamGui · LocalScript
Зачем: Кнопки команд.

-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- событие выбора команды
local teamEvent = RS:WaitForChild("TeamEvent")
-- TeamGui
local gui = script.Parent
-- окно с кнопками
local frame = gui:WaitForChild("Frame")

-- все объекты окна
for _, button in ipairs(frame:GetChildren()) do
    -- только кнопки
    if button:IsA("TextButton") then
        -- нажатие
        button.MouseButton1Click:Connect(function()
            -- имя кнопки = имя команды
            teamEvent:FireServer(button.Name)
            -- прячем окно
            gui.Enabled = false
        -- конец функции
        end)
    -- конец проверки
    end
-- конец перебора
end

TeamsServer

Где: ServerScriptService · Script
Зачем: Записывает в команду и переносит на её точку.

-- команды
local Teams = game:GetService("Teams")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- событие выбора
local teamEvent = RS:WaitForChild("TeamEvent")
-- true — идёт лобби, false — игра
local lobby = RS:WaitForChild("Lobby")

-- игрок нажал кнопку
teamEvent.OnServerEvent:Connect(function(player, teamName)
    -- от клиента пришло не имя — игнорируем
    if typeof(teamName) ~= "string" then return end
    -- команда с таким именем
    local team = Teams:FindFirstChild(teamName)
    -- нет такой или игрок уже в ней
    if not team or not team:IsA("Team") or player.Team == team then return end
    -- записываем в команду
    player.Team = team
    -- лобби или поле — смотря что идёт
    local folder = lobby.Value and workspace.LobbySpawn or workspace.GameSpawn
    -- точка появления команды
    player.RespawnLocation = folder:FindFirstChild(team.Name)
    -- возрождаем там
    player:LoadCharacter()
-- конец функции
end)

Проверка

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

Roblox · Capture the flag · lesson 2

Teams

A team selection window: the player presses "Синие" (Blue) or "Красные" (Red), joins the team and moves to its half of the lobby.

Structure

Blue — what we add in this lesson.

Teams
├─ Синие (Team) — TeamColor Really blue, AutoAssignable off
└─ Красные (Team) — TeamColor Really red, AutoAssignable off
Workspace
├─ Lobby (Model)
│  └─ Neutral (SpawnLocation) — Neutral on — until a team is chosen
├─ LobbySpawn (Folder)
│  └─ Синие, Красные (SpawnLocation) — Neutral off, the team's TeamColor
└─ GameSpawn (Folder) — on the field
   └─ Синие, Красные (SpawnLocation) — Neutral off, the team's TeamColor
ReplicatedStorage
├─ TeamEvent (RemoteEvent)
└─ Lobby (BoolValue) — Value on
ServerScriptService
└─ TeamsServer (Script)
StarterGui
└─ TeamGui (ScreenGui) — ResetOnSpawn off
   ├─ Frame (Frame)
   │  └─ Синие, Красные (TextButton) — button name = team name
   └─ TeamsLocal (LocalScript)

Steps

  1. Model → Service → Teams (if the service isn't in the Explorer). In Teams create two Teams: "Синие" (Blue, TeamColor Really blue) and "Красные" (Red, Really red). AutoAssignable off — the player chooses the team.
  2. In the lobby a SpawnLocation "Neutral" (Neutral on): players spawn here until they choose a team.
  3. Workspace → Folder "LobbySpawn": two SpawnLocations on the lobby halves — "Синие" and "Красные", Neutral off, TeamColor as the team's. The same kind of folder "GameSpawn" holds the points on the field.
  4. ReplicatedStorage → RemoteEvent "TeamEvent" and BoolValue "Lobby" (Value on — useful for the timer).
  5. StarterGui → ScreenGui "TeamGui" (ResetOnSpawn off — otherwise the window reappears after respawning). Inside a Frame with two TextButtons named exactly like the teams: "Синие" and "Красные".
  6. LocalScript "TeamsLocal" in TeamGui, Script "TeamsServer" in ServerScriptService.
  7. The server checks that the team exists: a client can send anything.

Scripts

TeamsLocal

Where: StarterGui → TeamGui · LocalScript
Why: Team buttons.

-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- the team selection event
local teamEvent = RS:WaitForChild("TeamEvent")
-- TeamGui
local gui = script.Parent
-- the window with the buttons
local frame = gui:WaitForChild("Frame")

-- all objects in the window
for _, button in ipairs(frame:GetChildren()) do
    -- buttons only
    if button:IsA("TextButton") then
        -- a click
        button.MouseButton1Click:Connect(function()
            -- button name = team name
            teamEvent:FireServer(button.Name)
            -- hide the window
            gui.Enabled = false
        -- end of function
        end)
    -- end of check
    end
-- end of loop
end

TeamsServer

Where: ServerScriptService · Script
Why: Puts the player into the team and moves them to its point.

-- teams
local Teams = game:GetService("Teams")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- the selection event
local teamEvent = RS:WaitForChild("TeamEvent")
-- true — lobby time, false — the game
local lobby = RS:WaitForChild("Lobby")

-- the player pressed a button
teamEvent.OnServerEvent:Connect(function(player, teamName)
    -- the client didn't send a name — ignore it
    if typeof(teamName) ~= "string" then return end
    -- the team with this name
    local team = Teams:FindFirstChild(teamName)
    -- no such team or the player is already in it
    if not team or not team:IsA("Team") or player.Team == team then return end
    -- put into the team
    player.Team = team
    -- lobby or field — depending on what's on
    local folder = lobby.Value and workspace.LobbySpawn or workspace.GameSpawn
    -- the team's spawn point
    player.RespawnLocation = folder:FindFirstChild(team.Name)
    -- respawn there
    player:LoadCharacter()
-- end of function
end)

Testing

Press Play (or Run) and make sure: