生命条
Coddy Roblox 游戏:塔防 课程的第 18 课,共 22 课。
每个敌人都有一个 BillboardGui、HealthBar:一种悬浮在部件上方并始终面向摄像机的 GUI。里面的深色 Back 框架中有一个绿色的 Fill。
填充条的宽度表示剩余生命值的比例。UDim2.fromScale(x, y) 会按父级的比例设置框架大小,因此,宽度为一半、高度为全高的填充条如下所示:
fill.Size = UDim2.fromScale(0.5, 1)Humanoid 的 HealthChanged 事件会传入新的生命值,因此生命条可以随之更新。
挑战
中等在每个敌人的血条上显示其生命值。
- 在
spawnEnemy中,连接 Humanoid 的HealthChanged。 - 在其中,将
enemy.HealthBar.Back.Fill.Size设置为UDim2.fromScale(health / enemy.Humanoid.MaxHealth, 1)。
按“开始”并建造一个 Archer:每当敌人受到攻击,它的绿色血条就会缩短。然后按“检查”。
亲手试试
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Debris = game:GetService("Debris")
local Settings = require(game.ReplicatedStorage.Settings)
local remotes = game.ReplicatedStorage.Remotes
local enemies = workspace.Enemies
local towers = workspace.Towers
local towerPad = {} -- 每座塔对应它所在的平台
print("The base can take " .. Settings.BaseHealth .. " hits")
-- 按顺序排列的路径点(名称依次为 1、2、3……)
local waypoints = workspace.Path.Waypoints:GetChildren()
table.sort(waypoints, function(a, b)
return tonumber(a.Name) < tonumber(b.Name)
end)
-- 基地的生命值作为 workspace 的属性:每个客户端都能读取
workspace:SetAttribute("BaseHealth", Settings.BaseHealth)
-- 每位玩家的排行榜上都有 Money
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local money = Instance.new("IntValue")
money.Name = "Money"
money.Value = Settings.StartMoney
money.Parent = leaderstats
end)
-- 一名敌人抵达了基地
local function damageBase(amount)
local health = math.max(0, workspace:GetAttribute("BaseHealth") - amount)
workspace:SetAttribute("BaseHealth", health)
print("Base: " .. health)
end
-- 让敌人沿路径前进。MoveTo 会在 8 秒后放弃,并通过返回结果表明这一点
-- (MoveToFinished 返回 false),所以要反复让移动较慢的敌人前进,直到它抵达。
local function walkPath(enemy)
local humanoid = enemy.Humanoid
for i = 2, #waypoints do
repeat
humanoid:MoveTo(waypoints[i].Position)
until humanoid.MoveToFinished:Wait() or not enemy.Parent
if not enemy.Parent then
return
end
end
-- 它抵达了基地
damageBase(Settings.Enemies[enemy.Name].Damage)
enemy:Destroy()
end
-- 一名新敌人出现在入口,沿路径前进
local function spawnEnemy(kind)
local enemy = ServerStorage.Enemies[kind]:Clone()
-- 放在第一个路径点的正上方
enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
local info = Settings.Enemies[kind]
enemy.Humanoid.MaxHealth = info.Health
enemy.Humanoid.Health = info.Health
enemy.Humanoid.WalkSpeed = info.Speed
enemy.Parent = enemies
-- 第 18 课:Health Bars 写在这里
enemy.Humanoid.Died:Connect(function()
-- 每位玩家都获得奖励
for _, player in Players:GetPlayers() do
player.leaderstats.Money.Value += info.Reward
end
enemy:Destroy()
end)
task.spawn(walkPath, enemy)
return enemy
end
-- 指定位置的范围内最近的存活敌人,找不到则返回 nil
local function nearestEnemy(position, range)
local best, bestDistance = nil, range
for _, enemy in enemies:GetChildren() do
local root = enemy:FindFirstChild("HumanoidRootPart")
if root and enemy.Humanoid.Health > 0 then
local distance = (root.Position - position).Magnitude
if distance <= bestDistance then
best, bestDistance = enemy, distance
end
end
end
return best
end
-- 从防御塔射向目标的一道闪光
local function beam(from, to)
local ray = Instance.new("Part")
ray.Anchored = true
ray.CanCollide = false
ray.CanTouch = false
ray.Material = Enum.Material.Neon
ray.Color = Color3.fromRGB(255, 240, 150)
ray.Size = Vector3.new(0.2, 0.2, (to - from).Magnitude)
ray.CFrame = CFrame.lookAt((from + to) / 2, to)
ray.Parent = workspace
Debris:AddItem(ray, 0.1)
end
-- Frost:敌人以原速度的一部分移动 2 秒
local function slow(enemy, factor)
if enemy:GetAttribute("Slowed") then
return
end
enemy:SetAttribute("Slowed", true)
local speed = Settings.Enemies[enemy.Name].Speed
enemy.Humanoid.WalkSpeed = speed * factor
task.delay(2, function()
if enemy.Parent then
enemy.Humanoid.WalkSpeed = speed
enemy:SetAttribute("Slowed", nil)
end
end)
end
-- 射击:对目标造成伤害;如果是 Cannon,还会伤害目标附近的所有敌人
local function shoot(tower, target, info)
local damage = info.Damage * tower:GetAttribute("Level")
local at = target.HumanoidRootPart.Position
if info.Splash then
for _, enemy in enemies:GetChildren() do
local root = enemy:FindFirstChild("HumanoidRootPart")
if root and (root.Position - at).Magnitude <= info.Splash then
enemy.Humanoid:TakeDamage(damage)
end
end
else
target.Humanoid:TakeDamage(damage)
end
if info.Slow and target.Parent then
slow(target, info.Slow)
end
beam(tower.Head.Position, at)
end
-- 防御塔的工作流程:瞄准范围内最近的敌人,射击,然后等待冷却结束
local function runTower(tower)
local info = Settings.Towers[tower.Name]
while tower.Parent do
local target = nearestEnemy(tower.Head.Position, info.Range)
if target then
tower.Head.CFrame = CFrame.lookAt(tower.Head.Position, target.HumanoidRootPart.Position)
shoot(tower, target, info)
task.wait(info.Cooldown)
else
task.wait(0.1)
end
end
end
-- 在塔位上建造一座防御塔
local function placeTower(pad, kind)
local tower = ServerStorage.Towers[kind]:Clone()
tower:PivotTo(pad.CFrame + Vector3.new(0, pad.Size.Y / 2 + 1, 0))
tower:SetAttribute("Level", 1)
tower.Parent = towers
pad:SetAttribute("Used", true)
towerPad[tower] = pad
task.spawn(runTower, tower)
end
-- 客户端请求在塔位上建造防御塔。检查所有条件:塔位真实存在且未被占用,
-- 防御塔类型真实存在,而且玩家有足够的钱支付。
remotes.Place.OnServerEvent:Connect(function(player, pad, kind)
if typeof(pad) ~= "Instance" or pad.Parent ~= workspace.Pads or pad:GetAttribute("Used") then
return
end
local info = typeof(kind) == "string" and Settings.Towers[kind]
if not info then
return
end
local money = player.leaderstats.Money
if money.Value < info.Price then
return
end
money.Value -= info.Price
placeTower(pad, kind)
end)
-- 升级:下一级的费用会越来越高,每升一级都会再次增加
-- 防御塔的基础伤害
remotes.Upgrade.OnServerEvent:Connect(function(player, tower)
if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
return
end
local level = tower:GetAttribute("Level")
local cost = math.floor(Settings.Towers[tower.Name].Price * Settings.UpgradeCost * level)
local money = player.leaderstats.Money
if money.Value < cost then
return
end
money.Value -= cost
tower:SetAttribute("Level", level + 1)
end)
-- 出售:返还一半价格,塔位重新空出来
remotes.Sell.OnServerEvent:Connect(function(player, tower)
if typeof(tower) ~= "Instance" or tower.Parent ~= towers then
return
end
player.leaderstats.Money.Value += math.floor(Settings.Towers[tower.Name].Price / 2)
towerPad[tower]:SetAttribute("Used", nil)
towerPad[tower] = nil
tower:Destroy()
end)
-- 一波敌人:逐个生成,然后等待它们全部消失
local function runWave(list)
for _, kind in list do
spawnEnemy(kind)
task.wait(Settings.SpawnGap)
end
while #enemies:GetChildren() > 0 do
task.wait(0.2)
end
end
-- 每波敌人都会在休息一段时间后出现
for i, list in Settings.Waves do
task.wait(Settings.WaveBreak)
runWave(list)
end
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Roblox 游戏:塔防中的所有课
自己练习: Roblox 在线编辑器