抵达基地
Coddy Roblox 游戏:塔防 课程的第 4 课,共 22 课。
到达路径终点的敌人会对基地造成伤害。基地的生命值应保存在服务器上,但每位玩家的屏幕都会显示它,因此要把它设为工作区的属性:在服务器上设置的属性会被每个客户端看到。
workspace:SetAttribute("BaseHealth", Settings.BaseHealth)
print(workspace:GetAttribute("BaseHealth")) --> 20damageBase(amount)会降低基地的生命值,但不会低于 0(使用math.max),并打印出生命值,这样你就能在 HUD 显示生命值之前,在输出面板中查看基地的生命值。经过最后一个路径点后,敌人会调用这个函数,然后使用Destroy离开游戏,否则这一波敌人就永远不会结束。
挑战
简单敌人到达基地时,对基地造成伤害。
- 排序路点后,将 workspace 属性
BaseHealth设置为Settings.BaseHealth。 - 编写
damageBase(amount):将BaseHealth降低amount,但不能低于 0,并执行print("Base: " .. health)。 - 在
walkPath末尾,调用damageBase(1)并销毁敌人。
按下“开始”:Zombie 走到基地后消失,Output 中会显示 Base: 19。然后按“检查”。
亲手试试
local Players = game:GetService("Players")
local ServerStorage = game:GetService("ServerStorage")
local Settings = require(game.ReplicatedStorage.Settings)
local enemies = workspace.Enemies
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)
-- 每个玩家的排行榜上都有 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)
-- 第 4 课:到达基地的代码写在这里
-- 让敌人沿路径行走。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
end
-- 一个新敌人出现在入口,沿路径行走
local function spawnEnemy(kind)
local enemy = ServerStorage.Enemies[kind]:Clone()
-- 放在第一个路径点的正上方
enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
enemy.Parent = enemies
task.spawn(walkPath, enemy)
return enemy
end
-- 目前只有一个敌人
spawnEnemy("Zombie")
Roblox 游戏:塔防中的所有课
自己练习: Roblox 在线编辑器