Roblox · Захват флага · урок 8
Итог курса на одной странице: полная структура захвата флага и финальные версии всех скриптов. Удобно сверить свою игру или собрать её заново.
Синим — что добавляем на этом уроке.
Teams — Синие, Красные (AutoAssignable выкл.) Workspace ├─ Lobby (Model) — комната на высоте 100, Neutral-спавн ├─ LobbySpawn, GameSpawn (Folder) — SpawnLocation «Синие» и «Красные» ├─ Field (Model) — земля, ограда, укрытия └─ Bases (Folder) └─ Синие, Красные (Model) — Stand, GivePart, ArmorGiver (ArmorScript), Flag → Hitbox, Pole, Cloth ReplicatedStorage ├─ TeamEvent, WinEvent (RemoteEvent) ├─ Lobby (BoolValue) └─ TimeLeft (IntValue) ServerScriptService └─ TeamsServer, FlagServer, TimerServer (Script) StarterGui — все ResetOnSpawn выкл. ├─ TeamGui (ScreenGui) — Frame → Синие, Красные; TeamsLocal ├─ TimerGui (ScreenGui) — TimerLabel, TimerLocal └─ WinnerGui (ScreenGui) — WinLabel, WinLocal
Где: 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)Где: 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Где: ServerScriptService · Script
Зачем: Раунды и победитель.
-- игроки
local Players = game:GetService("Players")
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- идёт лобби?
local lobby = RS:WaitForChild("Lobby")
-- сколько секунд осталось
local timeLeft = RS:WaitForChild("TimeLeft")
-- команды
local Teams = game:GetService("Teams")
-- объявить победителя
local winEvent = RS:WaitForChild("WinEvent")
-- секунд в лобби
local LOBBY_TIME = 30
-- секунд игры (5 минут)
local GAME_TIME = 300
-- всех игроков с командой — на точки своей команды
local function SendAll(folder)
-- каждый игрок
for _, player in ipairs(Players:GetPlayers()) do
-- команда выбрана
if player.Team then
-- точка команды в этой папке
player.RespawnLocation = folder:FindFirstChild(player.Team.Name)
-- возрождаем там (флаг сам вернётся)
player:LoadCharacter()
-- конец проверки
end
-- конец перебора
end
-- конец функции
end
-- обратный отсчёт
local function Countdown(seconds)
-- от seconds до 0
for t = seconds, 0, -1 do
-- игроки видят время
timeLeft.Value = t
-- секунда
task.wait(1)
-- конец цикла
end
-- конец функции
end
-- какая команда принесла больше флагов
local function Winner()
-- лучшая, её счёт, ничья ли
local bestTeam, bestScore, draw = nil, -1, false
-- каждая команда
for _, team in ipairs(Teams:GetTeams()) do
-- сумма флагов
local score = 0
-- игроки команды
for _, player in ipairs(team:GetPlayers()) do
-- таблица
local stats = player:FindFirstChild("leaderstats")
-- прибавляем
if stats then score += stats.Flags.Value end
-- конец перебора
end
-- больше всех
if score > bestScore then
-- новый лидер
bestTeam, bestScore, draw = team, score, false
-- столько же
elseif score == bestScore then
-- ничья
draw = true
-- конец проверки
end
-- конец перебора
end
-- белым
if not bestTeam or draw then return "Ничья!", Color3.new(1, 1, 1) end
-- цветом команды
return "Победили " .. bestTeam.Name .. "! Флагов: " .. bestScore, bestTeam.TeamColor.Color
-- конец функции
end
-- раунды по кругу
while true do
-- лобби
lobby.Value = true
-- все в лобби
SendAll(workspace.LobbySpawn)
-- ждём
Countdown(LOBBY_TIME)
-- игра
lobby.Value = false
-- обнуляем счёт
for _, player in ipairs(Players:GetPlayers()) do
-- таблица
local stats = player:FindFirstChild("leaderstats")
-- с нуля
if stats then stats.Flags.Value = 0 end
-- конец перебора
end
-- все на поле
SendAll(workspace.GameSpawn)
-- играем
Countdown(GAME_TIME)
-- показываем победителя всем
winEvent:FireAllClients(Winner())
-- пока читают
task.wait(5)
-- конец цикла
endГде: 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Где: StarterGui → TimerGui · LocalScript
Зачем: Время на экране.
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- идёт лобби?
local lobby = RS:WaitForChild("Lobby")
-- секунды
local timeLeft = RS:WaitForChild("TimeLeft")
-- надпись
local label = script.Parent:WaitForChild("TimerLabel")
-- обновить надпись
local function Update()
-- секунды
local t = timeLeft.Value
-- что идёт
local prefix = lobby.Value and "До начала: " or "До конца: "
-- минуты и секунды с нулём: 01:05
label.Text = prefix .. string.format("%02d:%02d", t // 60, t % 60)
-- конец функции
end
-- каждую секунду
timeLeft.Changed:Connect(Update)
-- лобби ↔ игра
lobby.Changed:Connect(Update)
-- сразу при входе
Update()Где: StarterGui → WinnerGui · LocalScript
Зачем: Победитель.
-- общее хранилище
local RS = game:GetService("ReplicatedStorage")
-- событие победы
local winEvent = RS:WaitForChild("WinEvent")
-- WinnerGui
local gui = script.Parent
-- надпись
local label = gui:WaitForChild("WinLabel")
-- сколько секунд показывать
local SHOW_TIME = 5
-- сервер объявил победителя
winEvent.OnClientEvent:Connect(function(text, color)
-- текст
label.Text = text
-- цвет команды
label.TextColor3 = color
-- показываем
gui.Enabled = true
-- ждём
task.wait(SHOW_TIME)
-- прячем
gui.Enabled = false
-- конец функции
end)Где: Bases → команда → ArmorGiver · Script
Зачем: Броня.
-- деталь, выдающая броню
local giver = script.Parent
-- сколько здоровья добавляет
local BONUS = 100
-- касание
giver.Touched:Connect(function(hit)
-- персонаж
local character = hit.Parent
-- Humanoid
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- не игрок, погиб или броня уже есть
if not humanoid or humanoid.Health <= 0 or character:GetAttribute("Armor") then return end
-- туловище R15 или R6
local torso = character:FindFirstChild("UpperTorso") or character:FindFirstChild("Torso")
-- нет туловища
if not torso then return end
-- у этого персонажа броня есть (после смерти — снова нет)
character:SetAttribute("Armor", true)
-- больше максимум
humanoid.MaxHealth += BONUS
-- полное здоровье
humanoid.Health = humanoid.MaxHealth
-- нагрудник
local plate = Instance.new("Part")
-- имя
plate.Name = "ArmorPlate"
-- чуть больше туловища
plate.Size = torso.Size + Vector3.new(0.3, 0.1, 0.3)
-- цвет как у выдачи
plate.Color = giver.Color
-- металл
plate.Material = Enum.Material.Metal
-- не мешает ходить
plate.CanCollide = false
-- лучи сквозь
plate.CanQuery = false
-- без веса
plate.Massless = true
-- на туловище
plate.CFrame = torso.CFrame
-- сварка
local weld = Instance.new("WeldConstraint")
-- туловище
weld.Part0 = torso
-- нагрудник
weld.Part1 = plate
-- в нагрудник
weld.Parent = plate
-- в персонажа
plate.Parent = character
-- конец функции
end)Запусти Play (или Run) и убедись:
Roblox · Capture the flag · lesson 8
The whole course on one page: the full capture-the-flag structure and final versions of all scripts. Handy for checking your game or rebuilding it.
Blue — what we add in this lesson.
Teams — Синие (Blue), Красные (Red) (AutoAssignable off) Workspace ├─ Lobby (Model) — a room at height 100, a Neutral spawn ├─ LobbySpawn, GameSpawn (Folder) — SpawnLocations "Синие" and "Красные" ├─ Field (Model) — ground, fence, cover └─ Bases (Folder) └─ Синие, Красные (Model) — Stand, GivePart, ArmorGiver (ArmorScript), Flag → Hitbox, Pole, Cloth ReplicatedStorage ├─ TeamEvent, WinEvent (RemoteEvent) ├─ Lobby (BoolValue) └─ TimeLeft (IntValue) ServerScriptService └─ TeamsServer, FlagServer, TimerServer (Script) StarterGui — all ResetOnSpawn off ├─ TeamGui (ScreenGui) — Frame → Синие, Красные; TeamsLocal ├─ TimerGui (ScreenGui) — TimerLabel, TimerLocal └─ WinnerGui (ScreenGui) — WinLabel, WinLocal
Where: ServerScriptService · Script
Why: Team selection.
-- 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)Where: ServerScriptService · Script
Why: Flags and points.
-- 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
endWhere: ServerScriptService · Script
Why: Rounds and the winner.
-- players
local Players = game:GetService("Players")
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- is it lobby time?
local lobby = RS:WaitForChild("Lobby")
-- how many seconds are left
local timeLeft = RS:WaitForChild("TimeLeft")
-- teams
local Teams = game:GetService("Teams")
-- announce the winner
local winEvent = RS:WaitForChild("WinEvent")
-- seconds in the lobby
local LOBBY_TIME = 30
-- seconds of play (5 minutes)
local GAME_TIME = 300
-- move all players with a team to their team's points
local function SendAll(folder)
-- each player
for _, player in ipairs(Players:GetPlayers()) do
-- a team is chosen
if player.Team then
-- the team's point in this folder
player.RespawnLocation = folder:FindFirstChild(player.Team.Name)
-- respawn there (the flag returns by itself)
player:LoadCharacter()
-- end of check
end
-- end of loop
end
-- end of function
end
-- the countdown
local function Countdown(seconds)
-- from seconds down to 0
for t = seconds, 0, -1 do
-- players see the time
timeLeft.Value = t
-- a second
task.wait(1)
-- end of loop
end
-- end of function
end
-- which team brought more flags
local function Winner()
-- the best team, its score, is it a draw
local bestTeam, bestScore, draw = nil, -1, false
-- each team
for _, team in ipairs(Teams:GetTeams()) do
-- the flag total
local score = 0
-- the team's players
for _, player in ipairs(team:GetPlayers()) do
-- the board
local stats = player:FindFirstChild("leaderstats")
-- add
if stats then score += stats.Flags.Value end
-- end of loop
end
-- the most
if score > bestScore then
-- a new leader
bestTeam, bestScore, draw = team, score, false
-- the same amount
elseif score == bestScore then
-- a draw
draw = true
-- end of check
end
-- end of loop
end
-- in white
if not bestTeam or draw then return "Ничья!", Color3.new(1, 1, 1) end
-- in the team color
return "Победили " .. bestTeam.Name .. "! Флагов: " .. bestScore, bestTeam.TeamColor.Color
-- end of function
end
-- rounds in a loop
while true do
-- the lobby
lobby.Value = true
-- everyone to the lobby
SendAll(workspace.LobbySpawn)
-- wait
Countdown(LOBBY_TIME)
-- the game
lobby.Value = false
-- reset the score
for _, player in ipairs(Players:GetPlayers()) do
-- the board
local stats = player:FindFirstChild("leaderstats")
-- from zero
if stats then stats.Flags.Value = 0 end
-- end of loop
end
-- everyone to the field
SendAll(workspace.GameSpawn)
-- play
Countdown(GAME_TIME)
-- show the winner to everyone
winEvent:FireAllClients(Winner())
-- while they read
task.wait(5)
-- end of loop
endWhere: 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
endWhere: StarterGui → TimerGui · LocalScript
Why: Time on screen.
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- is it lobby time?
local lobby = RS:WaitForChild("Lobby")
-- seconds
local timeLeft = RS:WaitForChild("TimeLeft")
-- a label
local label = script.Parent:WaitForChild("TimerLabel")
-- update the label
local function Update()
-- seconds
local t = timeLeft.Value
-- what's on
local prefix = lobby.Value and "До начала: " or "До конца: "
-- minutes and seconds with a zero: 01:05
label.Text = prefix .. string.format("%02d:%02d", t // 60, t % 60)
-- end of function
end
-- every second
timeLeft.Changed:Connect(Update)
-- lobby ↔ game
lobby.Changed:Connect(Update)
-- right on joining
Update()Where: StarterGui → WinnerGui · LocalScript
Why: The winner.
-- shared storage
local RS = game:GetService("ReplicatedStorage")
-- the victory event
local winEvent = RS:WaitForChild("WinEvent")
-- WinnerGui
local gui = script.Parent
-- a label
local label = gui:WaitForChild("WinLabel")
-- how many seconds to show
local SHOW_TIME = 5
-- the server announced the winner
winEvent.OnClientEvent:Connect(function(text, color)
-- text
label.Text = text
-- the team color
label.TextColor3 = color
-- show it
gui.Enabled = true
-- wait
task.wait(SHOW_TIME)
-- hide
gui.Enabled = false
-- end of function
end)Where: Bases → team → ArmorGiver · Script
Why: Armor.
-- the part that gives armor
local giver = script.Parent
-- how much health it adds
local BONUS = 100
-- touch
giver.Touched:Connect(function(hit)
-- the character
local character = hit.Parent
-- Humanoid
local humanoid = character:FindFirstChildOfClass("Humanoid")
-- not a player, dead or already has armor
if not humanoid or humanoid.Health <= 0 or character:GetAttribute("Armor") then return end
-- the R15 or R6 torso
local torso = character:FindFirstChild("UpperTorso") or character:FindFirstChild("Torso")
-- no torso
if not torso then return end
-- this character has armor (after death — none again)
character:SetAttribute("Armor", true)
-- a higher maximum
humanoid.MaxHealth += BONUS
-- full health
humanoid.Health = humanoid.MaxHealth
-- the chest plate
local plate = Instance.new("Part")
-- name
plate.Name = "ArmorPlate"
-- slightly bigger than the torso
plate.Size = torso.Size + Vector3.new(0.3, 0.1, 0.3)
-- the same color as the giver
plate.Color = giver.Color
-- metal
plate.Material = Enum.Material.Metal
-- doesn't get in the way
plate.CanCollide = false
-- rays pass through
plate.CanQuery = false
-- weightless
plate.Massless = true
-- on the torso
plate.CFrame = torso.CFrame
-- the weld
local weld = Instance.new("WeldConstraint")
-- the torso
weld.Part0 = torso
-- the chest plate
weld.Part1 = plate
-- into the chest plate
weld.Parent = plate
-- into the character
plate.Parent = character
-- end of function
end)Press Play (or Run) and make sure: