Walk the Path
Lesson 3 of 22 in Coddy's Roblox Game: Tower Defense course.
A Humanoid walks with MoveTo, and its MoveToFinished event fires when it arrives. It gives up after 8 seconds and fires with false, so a slow enemy on a long stretch is sent again until it gets there:
repeat
humanoid:MoveTo(points[4].Position)
until humanoid.MoveToFinished:Wait()Walking the whole path takes time, so walkPath runs in its own thread with task.spawn(walkPath, enemy), and spawnEnemy carries on and returns.
Challenge
EasyMake the Zombie walk the path.
- Write
walkPath(enemy): fori = 2, #waypoints, repeatenemy.Humanoid:MoveTo(waypoints[i].Position)untilMoveToFinished:Wait()says it arrived ornot enemy.Parent; return if the enemy is gone. - In
spawnEnemy, beforereturn enemy, addtask.spawn(walkPath, enemy).
Press Play: the Zombie walks the path to the blue base. Then Check.
Try it yourself
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")
-- The waypoints, in order (they are named 1, 2, 3...)
local waypoints = workspace.Path.Waypoints:GetChildren()
table.sort(waypoints, function(a, b)
return tonumber(a.Name) < tonumber(b.Name)
end)
-- Every player gets Money on the leaderboard
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)
-- Lesson 3: Walk the Path goes here
-- A new enemy at the gate, walking the path
local function spawnEnemy(kind)
local enemy = ServerStorage.Enemies[kind]:Clone()
-- dropped in just above the first waypoint
enemy:PivotTo(waypoints[1].CFrame + Vector3.new(0, 5, 0))
enemy.Parent = enemies
return enemy
end
-- One enemy, for now
spawnEnemy("Zombie")
All lessons in Roblox Game: Tower Defense
Practice on your own: Roblox playground