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()
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