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

Флаги: захват и доставка

Один серверный скрипт управляет всеми флагами: схватил чужой — он за спиной; донёс до своей базы — очко команде; погиб — флаг вернулся домой.

Структура

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

Workspace
└─ Bases (Folder)
ServerScriptService
└─ FlagServer (Script)
Players → игрок — создаёт скрипт
└─ leaderstats (Folder)
   └─ Flags (IntValue) — принесённые флаги

Шаги

  1. ServerScriptService → Script «FlagServer». В методичке было три скрипта в каждом флаге — один общий проще и надёжнее.
  2. Свой флаг взять нельзя, чужой — можно, если у игрока ещё нет другого флага.
  3. Флаг не переносится внутрь персонажа, как в методичке, а приваривается к спине (Weld с C0). Если положить флаг в персонажа, он удалится вместе с ним при выходе игрока из игры.
  4. Атрибут HasFlag у игрока — имя базы, чей флаг он несёт.
  5. Погиб, вышел или возродился — флаг сам возвращается на подставку, все подписки снимаются: флаг не «двоится».
  6. Очко засчитывается, когда носитель касается GivePart своей команды. Флаг возвращается домой, у игрока +1 Flags.
  7. Проверка вдвоём: Test → Clients and Servers → 2 Players, выбери разные команды.

Скрипты

FlagServer

Где: ServerScriptService · Script
Зачем: Захват, перенос, возврат флагов и очки.

-- игроки
local Players = game:GetService("Players")
-- команды
local Teams = game:GetService("Teams")
-- базы; имя базы = имя команды
local bases = workspace:WaitForChild("Bases")
-- имя базы → функция «вернуть её флаг»
local returns = {}

-- игрок зашёл
Players.PlayerAdded:Connect(function(player)
    -- таблица по Tab
    local leaderstats = Instance.new("Folder")
    -- имя строго такое
    leaderstats.Name = "leaderstats"
    -- в игрока
    leaderstats.Parent = player
    -- принесённые флаги
    local flags = Instance.new("IntValue")
    -- столбец
    flags.Name = "Flags"
    -- в таблицу
    flags.Parent = leaderstats
-- конец функции
end)

-- живой игрок, чья деталь коснулась
local function GetPlayer(hit)
    -- модель персонажа
    local character = hit.Parent
    -- Humanoid
    local humanoid = character and character:FindFirstChildOfClass("Humanoid")
    -- не персонаж или погиб
    if not humanoid or humanoid.Health <= 0 then return nil end
    -- игрок
    return Players:GetPlayerFromCharacter(character)
-- конец функции
end

-- настраиваем одну базу
local function Setup(base)
    -- команда этой базы
    local team = Teams:WaitForChild(base.Name)
    -- модель флага
    local flag = base:WaitForChild("Flag")
    -- главная деталь флага
    local hitbox = flag:WaitForChild("Hitbox")
    -- куда приносить чужой флаг
    local givePart = base:WaitForChild("GivePart")
    -- место флага на подставке
    local home = hitbox.CFrame
    -- кто несёт флаг
    local carrier = nil
    -- подписки на смерть носителя
    local connections = {}

    -- флаг — обратно на подставку
    local function ReturnFlag()
        -- отписываемся
        for _, connection in ipairs(connections) do connection:Disconnect() end
        -- список пуст
        table.clear(connections)
        -- у игрока больше нет флага
        if carrier then carrier:SetAttribute("HasFlag", nil) end
        -- никто не несёт
        carrier = nil
        -- сварка со спиной
        local weld = hitbox:FindFirstChild("CarryWeld")
        -- убираем
        if weld then weld:Destroy() end
        -- закрепляем
        hitbox.Anchored = true
        -- на подставку
        hitbox.CFrame = home
    -- конец функции
    end
    -- чтобы другая база могла вернуть этот флаг
    returns[base.Name] = ReturnFlag

    -- кто-то коснулся флага
    hitbox.Touched:Connect(function(hit)
        -- флаг уже несут
        if carrier then return end
        -- игрок
        local player = GetPlayer(hit)
        -- свой флаг не берут
        if not player or not player.Team or player.Team == team then return end
        -- два флага сразу нельзя
        if player:GetAttribute("HasFlag") then return end
        -- Humanoid носителя
        local humanoid = player.Character:FindFirstChildOfClass("Humanoid")
        -- к нему крепим
        local root = player.Character:FindFirstChild("HumanoidRootPart")
        -- персонаж не собран
        if not root then return end
        -- запоминаем носителя
        carrier = player
        -- чей флаг у игрока
        player:SetAttribute("HasFlag", base.Name)
        -- сварка со смещением
        local weld = Instance.new("Weld")
        -- имя — чтобы найти и убрать
        weld.Name = "CarryWeld"
        -- спина игрока
        weld.Part0 = root
        -- флаг
        weld.Part1 = hitbox
        -- чуть выше и за спиной
        weld.C0 = CFrame.new(0, 1.5, 1.2)
        -- в флаг
        weld.Parent = hitbox
        -- флаг едет за игроком
        hitbox.Anchored = false
        -- погиб — флаг домой
        table.insert(connections, humanoid.Died:Connect(ReturnFlag))
        -- вышел или возродился — тоже
        table.insert(connections, player.CharacterRemoving:Connect(ReturnFlag))
    -- конец функции
    end)

    -- кто-то пришёл на свою базу
    givePart.Touched:Connect(function(hit)
        -- игрок
        local player = GetPlayer(hit)
        -- только игроки этой команды
        if not player or player.Team ~= team then return end
        -- чей флаг принёс
        local enemyName = player:GetAttribute("HasFlag")
        -- ничего не несёт
        if not enemyName or not returns[enemyName] then return end
        -- чужой флаг возвращается на свою подставку
        returns[enemyName]()
        -- таблица игрока
        local stats = player:FindFirstChild("leaderstats")
        -- +1 флаг
        if stats then stats.Flags.Value += 1 end
    -- конец функции
    end)
-- конец функции
end

-- все базы
for _, base in ipairs(bases:GetChildren()) do
    -- настраиваем
    task.spawn(Setup, base)
-- конец перебора
end

Проверка

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

Roblox · Capture the flag · lesson 4

Flags: capture and delivery

One server script controls all flags: grab the enemy flag and it's on your back; bring it to your base and your team scores; die and the flag returns home.

Structure

Blue — what we add in this lesson.

Workspace
└─ Bases (Folder)
ServerScriptService
└─ FlagServer (Script)
Players → игрок — created by the script
└─ leaderstats (Folder)
   └─ Flags (IntValue) — delivered flags

Steps

  1. ServerScriptService → Script "FlagServer". The workbook had three scripts in each flag — one shared script is simpler and more reliable.
  2. You can't take your own flag; you can take the enemy's if you don't already carry one.
  3. The flag isn't moved inside the character as in the workbook — it's welded to the back (a Weld with C0). If you put the flag inside the character, it gets deleted with it when the player leaves.
  4. The player's HasFlag attribute is the name of the base whose flag they carry.
  5. Die, leave or respawn — the flag returns to its stand by itself and all connections are removed: the flag never "duplicates".
  6. A point counts when the carrier touches their own team's GivePart. The flag goes home, the player gets +1 Flags.
  7. Test with two: Test → Clients and Servers → 2 Players, pick different teams.

Scripts

FlagServer

Where: ServerScriptService · Script
Why: Capturing, carrying and returning flags, and scoring.

-- players
local Players = game:GetService("Players")
-- teams
local Teams = game:GetService("Teams")
-- bases; base name = team name
local bases = workspace:WaitForChild("Bases")
-- base name → a "return its flag" function
local returns = {}

-- 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
    -- delivered flags
    local flags = Instance.new("IntValue")
    -- the column
    flags.Name = "Flags"
    -- into the board
    flags.Parent = leaderstats
-- end of function
end)

-- the living player whose part touched
local function GetPlayer(hit)
    -- the character model
    local character = hit.Parent
    -- Humanoid
    local humanoid = character and character:FindFirstChildOfClass("Humanoid")
    -- not a character or dead
    if not humanoid or humanoid.Health <= 0 then return nil end
    -- the player
    return Players:GetPlayerFromCharacter(character)
-- end of function
end

-- set up one base
local function Setup(base)
    -- this base's team
    local team = Teams:WaitForChild(base.Name)
    -- the flag model
    local flag = base:WaitForChild("Flag")
    -- the flag's main part
    local hitbox = flag:WaitForChild("Hitbox")
    -- where to bring the enemy flag
    local givePart = base:WaitForChild("GivePart")
    -- the flag's place on the stand
    local home = hitbox.CFrame
    -- who carries the flag
    local carrier = nil
    -- connections to the carrier's death
    local connections = {}

    -- flag back onto the stand
    local function ReturnFlag()
        -- disconnect
        for _, connection in ipairs(connections) do connection:Disconnect() end
        -- the list is empty
        table.clear(connections)
        -- the player no longer has a flag
        if carrier then carrier:SetAttribute("HasFlag", nil) end
        -- nobody carries it
        carrier = nil
        -- the weld to the back
        local weld = hitbox:FindFirstChild("CarryWeld")
        -- remove it
        if weld then weld:Destroy() end
        -- anchor it
        hitbox.Anchored = true
        -- onto the stand
        hitbox.CFrame = home
    -- end of function
    end
    -- so the other base can return this flag
    returns[base.Name] = ReturnFlag

    -- someone touched the flag
    hitbox.Touched:Connect(function(hit)
        -- the flag is already carried
        if carrier then return end
        -- the player
        local player = GetPlayer(hit)
        -- you don't take your own flag
        if not player or not player.Team or player.Team == team then return end
        -- two flags at once aren't allowed
        if player:GetAttribute("HasFlag") then return end
        -- the carrier's Humanoid
        local humanoid = player.Character:FindFirstChildOfClass("Humanoid")
        -- attach it to this
        local root = player.Character:FindFirstChild("HumanoidRootPart")
        -- the character isn't assembled
        if not root then return end
        -- remember the carrier
        carrier = player
        -- whose flag the player has
        player:SetAttribute("HasFlag", base.Name)
        -- a weld with an offset
        local weld = Instance.new("Weld")
        -- a name — to find and remove it
        weld.Name = "CarryWeld"
        -- the player's back
        weld.Part0 = root
        -- the flag
        weld.Part1 = hitbox
        -- slightly higher and behind the back
        weld.C0 = CFrame.new(0, 1.5, 1.2)
        -- into the flag
        weld.Parent = hitbox
        -- the flag moves with the player
        hitbox.Anchored = false
        -- died — flag goes home
        table.insert(connections, humanoid.Died:Connect(ReturnFlag))
        -- left or respawned — the same
        table.insert(connections, player.CharacterRemoving:Connect(ReturnFlag))
    -- end of function
    end)

    -- someone came to their base
    givePart.Touched:Connect(function(hit)
        -- the player
        local player = GetPlayer(hit)
        -- only players of this team
        if not player or player.Team ~= team then return end
        -- whose flag they brought
        local enemyName = player:GetAttribute("HasFlag")
        -- carries nothing
        if not enemyName or not returns[enemyName] then return end
        -- the enemy flag returns to its stand
        returns[enemyName]()
        -- the player's board
        local stats = player:FindFirstChild("leaderstats")
        -- +1 flag
        if stats then stats.Flags.Value += 1 end
    -- end of function
    end)
-- end of function
end

-- all bases
for _, base in ipairs(bases:GetChildren()) do
    -- set up
    task.spawn(Setup, base)
-- end of loop
end

Testing

Press Play (or Run) and make sure: