local base = script.Parent
local health = base.Health
local label = base.BillboardGui.TextLabel
local function update()
if health.Value > 0 then
label.Text = "Base: " .. health.Value
else
label.Text = "Game over"
end
end
health.Changed:Connect(update)
update()
按 Play。每隔 3 秒,1 号 Part 那里就会出现一个红色的球,并沿着路线移动。它走到终点时,基地会失去 1 点生命值。
ServerScriptService > Waves
local TweenService = game:GetService("TweenService")
local ServerStorage = game:GetService("ServerStorage")
local path = workspace:WaitForChild("Path")
local enemies = workspace:WaitForChild("Enemies")
local base = workspace:WaitForChild("Base")
local SPEED = 8
local function walk(enemy)
for i = 2, #path:GetChildren() do
local target = path[tostring(i)].Position + Vector3.new(0, 2, 0)
local distance = (target - enemy.Position).Magnitude
local info = TweenInfo.new(distance / SPEED, Enum.EasingStyle.Linear)
local tween = TweenService:Create(enemy, info, {Position = target})
tween:Play()
tween.Completed:Wait()
if not enemy.Parent then return end
end
base.Health.Value = math.max(0, base.Health.Value - 1)
enemy:Destroy()
end
while base.Health.Value > 0 do
task.wait(3)
local enemy = ServerStorage.Enemy:Clone()
enemy.Position = path["1"].Position + Vector3.new(0, 2, 0)
enemy.Parent = enemies
task.spawn(walk, enemy)
end
每一部分的作用
Clone 会从 ServerStorage 里复制一个 Enemy 模板。
walk 函数会让敌人按顺序走向路线上的每个 Part。distance / SPEED 让敌人在长短不同的路段上速度都一样。
task.spawn 让每个敌人各走各的,这样循环就可以继续派出新的敌人。
更多细节
脚本会在新的标签页里打开。点一下代码里面,按 Ctrl+A,再按 Ctrl+V,替换掉所有内容。
游戏运行时,敌人会出现在 Enemies 文件夹里。你可以在 Explorer 里看到它们。
如果还没有防御塔,每个敌人都会到达基地。10 个敌人过后,标签会显示 Game over,不会再有敌人出现。
local tower = script.Parent
local enemies = workspace:WaitForChild("Enemies")
local RANGE = 25
local DAMAGE = 1
while true do
task.wait(1)
local target = nil
local closest = RANGE
for _, enemy in ipairs(enemies:GetChildren()) do
local distance = (enemy.Position - tower.Position).Magnitude
if distance < closest then
target = enemy
closest = distance
end
end
if target then
target.Health.Value -= DAMAGE
if target.Health.Value <= 0 then
target:Destroy()
else
target.Color = Color3.new(1, 1, 1)
task.wait(0.1)
target.Color = Color3.fromRGB(255, 60, 60)
end
end
end