Menu
CoddyTech

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 icon

Challenge

Easy

Make the Zombie walk the path.

  1. Write walkPath(enemy): for i = 2, #waypoints, repeat enemy.Humanoid:MoveTo(waypoints[i].Position) until MoveToFinished:Wait() says it arrived or not enemy.Parent; return if the enemy is gone.
  2. In spawnEnemy, before return enemy, add task.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