Start building

How to make a tower defense game on Roblox: paths, waves and towers

Enemies that follow a path, waves from a config table, and towers that place, aim and upgrade without trusting the client: the whole loop in Luau.

A tower defense map in Roblox Studio: a winding path, towers on wooden posts and slimes on wave 1 of 20, with a tower bar of archer, cannon, frost and laser.
On this page
  1. How the pieces fit together
  2. Build the enemy path with waypoints
  3. Make enemies walk the path
  4. Waves, base health and game over
  5. Place towers with a server check
  6. Target enemies with one loop for every tower
  7. Add upgrades with a ProximityPrompt
  8. Keep it fast
  9. Questions

To make a tower defense game on Roblox, you need five systems: a path made of numbered waypoint parts, enemies that walk it, a wave spawner, base health that ends the game, and towers that players place and the server aims. This guide builds each one in Roblox Studio with Luau you can paste in, checked on the server.

If Studio is new to you, read how to make a Roblox game first.

How the pieces fit together

The server owns everything that matters: enemies, health, cash and towers. The client only shows a ghost preview and asks to place. Set up Explorer like this first:

WhatWhereNotes
Waypoints folder with parts named 1, 2, 3...WorkspaceAnchored, CanCollide off, along the route
Enemies and Towers folders (empty)WorkspaceFilled while the game runs
EnemyModels folder: Zombie, Runner, TankServerStorageModels with parts anchored and CanCollide off
TowerModels folder: ArcherReplicatedStorageParts anchored, PrimaryPart set; the client clones it for the ghost
PlaceTower RemoteEventReplicatedStorageThe client's placement request
TowerDefense ScriptServerScriptServiceAll server code below goes in here, in order

Build the enemy path with waypoints

Place parts along the route, named 1, 2, 3 in walking order, with the last one at your base. Set their Transparency to 1 once the route looks right.

ScriptServerScriptService
-- Script in ServerScriptService named TowerDefense, part 1: read the path
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ServerStorage = game:GetService("ServerStorage")

local waypointParts = workspace:WaitForChild("Waypoints"):GetChildren()
table.sort(waypointParts, function(a, b)
	return tonumber(a.Name) < tonumber(b.Name)
end)

local points = {} -- waypoint positions in walking order
local lengths = { 0 } -- distance along the path to each waypoint
for i, part in waypointParts do
	points[i] = part.Position
	if i > 1 then
		lengths[i] = lengths[i - 1] + (points[i] - points[i - 1]).Magnitude
	end
end
local pathLength = lengths[#points]

-- where an enemy stands after walking a distance, and which way it faces
local function pointAlongPath(distance)
	for i = 2, #points do
		if distance <= lengths[i] then
			local alpha = (distance - lengths[i - 1]) / (lengths[i] - lengths[i - 1])
			return points[i - 1]:Lerp(points[i], alpha), (points[i] - points[i - 1]).Unit
		end
	end
	return points[#points], Vector3.zAxis
end

Sorting with tonumber keeps waypoint 10 after 9. Measuring the path as one number, studs walked, makes the rest easy: moving an enemy adds to it, and the enemy in front has the biggest one.

Make enemies walk the path

Each enemy is a record with its model, health and distance walked. One Heartbeat loop moves them all.

Script
-- Same Script, part 2: enemies walk the path, and leaks hurt the base
local ENEMIES = {
	Zombie = { health = 10, speed = 6, reward = 5, damage = 1 },
	Runner = { health = 6, speed = 12, reward = 6, damage = 1 },
	Tank = { health = 80, speed = 3, reward = 30, damage = 10 },
}
local enemyModels = ServerStorage:WaitForChild("EnemyModels")
local enemies = {} -- every enemy on the path

workspace:SetAttribute("BaseHealth", 100)

local function spawnEnemy(kind)
	local model = enemyModels[kind]:Clone()
	model.Parent = workspace.Enemies
	local lift = model:GetExtentsSize().Y / 2
	model:PivotTo(CFrame.new(points[1] + Vector3.yAxis * lift))
	table.insert(enemies, { model = model, stats = ENEMIES[kind], health = ENEMIES[kind].health, distance = 0, lift = lift })
end

RunService.Heartbeat:Connect(function(dt)
	for i = #enemies, 1, -1 do
		local enemy = enemies[i]
		if enemy.dead then
			table.remove(enemies, i)
			continue
		end
		enemy.distance += enemy.stats.speed * dt
		if enemy.distance >= pathLength then
			local health = workspace:GetAttribute("BaseHealth") - enemy.stats.damage
			workspace:SetAttribute("BaseHealth", math.max(0, health))
			enemy.model:Destroy()
			table.remove(enemies, i)
		else
			local position, direction = pointAlongPath(enemy.distance)
			position += Vector3.yAxis * enemy.lift
			enemy.model:PivotTo(CFrame.lookAt(position, position + direction))
		end
	end
end)

Speed is in studs per second, multiplied by the frame time dt. An enemy that reaches the end subtracts its damage from BaseHealth, an attribute on Workspace that clients can read for a health bar. The loop runs backwards so removing an enemy never skips the next one.

The other common approach is a Humanoid per enemy: MoveTo each waypoint and wait for MoveToFinished. You get walk animations, but Humanoids cost more, and MoveTo gives up after 8 seconds, so keep waypoints close.

Waves, base health and game over

Waves live in a config table, so balancing the game means editing numbers, not code. Each wave is a list of groups: which enemy, how many, and the gap in seconds between spawns.

Script
-- Same Script, part 3: waves from a config table, then win or lose
local WAVES = {
	{ { enemy = "Zombie", count = 8, gap = 1 } },
	{ { enemy = "Zombie", count = 12, gap = 0.8 }, { enemy = "Runner", count = 5, gap = 0.5 } },
	{ { enemy = "Tank", count = 2, gap = 3 }, { enemy = "Runner", count = 10, gap = 0.4 } },
}

local function baseAlive()
	return workspace:GetAttribute("BaseHealth") > 0
end

task.spawn(function()
	task.wait(15) -- time for players to join and place their first towers
	for number, wave in WAVES do
		workspace:SetAttribute("Wave", number)
		for _, group in wave do
			for _ = 1, group.count do
				if baseAlive() then
					spawnEnemy(group.enemy)
					task.wait(group.gap)
				end
			end
		end
		repeat
			task.wait(0.5)
		until #enemies == 0 or not baseAlive()
		if not baseAlive() then
			break
		end
		task.wait(5) -- a short break between waves
	end
	for _, enemy in enemies do
		enemy.model:Destroy()
	end
	table.clear(enemies)
	workspace:SetAttribute("Result", if baseAlive() then "Victory" else "Defeat")
end)

The runner sits in task.spawn, so the rest of the Script keeps running. The round stops when the base hits 0, and a TextLabel can show Wave and Result by listening with GetAttributeChangedSignal. A finished game would reset the map or return players to a lobby here.

Place towers with a server check

First, tower stats and each player's cash, kept in leaderstats so it shows on the player list:

Script
-- Same Script, part 4: tower stats and starting cash
local TOWERS = {
	Archer = {
		cost = 100,
		targeting = "First", -- or "Closest"
		levels = {
			{ damage = 3, range = 24, cooldown = 0.8 },
			{ damage = 5, range = 28, cooldown = 0.6, price = 120 },
			{ damage = 9, range = 32, cooldown = 0.45, price = 250 },
		},
	},
}
local towers = {} -- placed towers, keyed by their model

local function giveCash(player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	local cash = Instance.new("IntValue")
	cash.Name = "Cash"
	cash.Value = 250
	cash.Parent = leaderstats
	leaderstats.Parent = player
end
Players.PlayerAdded:Connect(giveCash)
for _, player in Players:GetPlayers() do
	giveCash(player)
end

On the client, pressing 1 shows a green-tinted ghost tower that follows the mouse, and clicking asks the server to place it.

LocalScriptStarterPlayerScripts
-- LocalScript in StarterPlayerScripts: press 1 for a ghost tower, click to place
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local UserInputService = game:GetService("UserInputService")

local placeTower = ReplicatedStorage:WaitForChild("PlaceTower")
local towerModels = ReplicatedStorage:WaitForChild("TowerModels")
local ghost, selected = nil, nil

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude

local function groundUnderMouse()
	local mouse = UserInputService:GetMouseLocation()
	local ray = workspace.CurrentCamera:ViewportPointToRay(mouse.X, mouse.Y)
	params.FilterDescendantsInstances = { ghost, Players.LocalPlayer.Character }
	local result = workspace:Raycast(ray.Origin, ray.Direction * 500, params)
	return result and result.Position
end

local function startPlacing(kind)
	if ghost then
		ghost:Destroy()
	end
	selected, ghost = kind, towerModels[kind]:Clone()
	local tint = Instance.new("Highlight")
	tint.FillColor = Color3.fromRGB(90, 255, 140)
	tint.Parent = ghost
	ghost.Parent = workspace
end

RunService.RenderStepped:Connect(function()
	local spot = ghost and groundUnderMouse()
	if spot then
		ghost:PivotTo(CFrame.new(spot + Vector3.yAxis * ghost:GetExtentsSize().Y / 2))
	end
end)

UserInputService.InputBegan:Connect(function(input, processed)
	if processed then
		return
	elseif input.KeyCode == Enum.KeyCode.One then
		startPlacing("Archer")
	elseif input.UserInputType == Enum.UserInputType.MouseButton1 and ghost then
		local spot = groundUnderMouse()
		if spot then
			placeTower:FireServer(selected, spot)
		end
		ghost:Destroy()
		ghost = nil
	end
end)

The client sends only a tower name and a position, never a price. The server checks the rest:

Script
-- Same Script, part 5: check every placement request on the server
local towerModels = ReplicatedStorage:WaitForChild("TowerModels")
local placeTower = ReplicatedStorage:WaitForChild("PlaceTower")
local PATH_CLEARANCE = 6 -- studs from the middle of the path

local overlap = OverlapParams.new()
overlap.FilterType = Enum.RaycastFilterType.Include
overlap.FilterDescendantsInstances = { workspace.Towers }

local function distanceToPath(position)
	local closest = math.huge
	for i = 2, #points do
		local a, b = points[i - 1], points[i]
		local t = math.clamp((position - a):Dot(b - a) / (b - a):Dot(b - a), 0, 1)
		closest = math.min(closest, (position - a:Lerp(b, t)).Magnitude)
	end
	return closest
end

local function labelPrompt(prompt, tower)
	local after = TOWERS[tower.kind].levels[tower.level + 1]
	prompt.ObjectText = tower.owner.DisplayName .. "'s " .. tower.kind .. " (level " .. tower.level .. ")"
	prompt.ActionText = if after then "Upgrade for " .. after.price else "Max level"
	prompt.Enabled = after ~= nil
end

placeTower.OnServerEvent:Connect(function(player, kind, position)
	local config = TOWERS[kind]
	local cash = player:FindFirstChild("leaderstats") and player.leaderstats:FindFirstChild("Cash")
	if not config or typeof(position) ~= "Vector3" or not cash then
		return
	end
	local size = towerModels[kind]:GetExtentsSize()
	local spot = CFrame.new(position + Vector3.yAxis * size.Y / 2)
	if cash.Value < config.cost
		or distanceToPath(position) < PATH_CLEARANCE
		or #workspace:GetPartBoundsInBox(spot, size, overlap) > 0
	then
		return
	end
	cash.Value -= config.cost
	local model = towerModels[kind]:Clone()
	model:PivotTo(spot)
	model.Parent = workspace.Towers
	local tower = { owner = player, kind = kind, level = 1, position = position, ready = 0 }
	towers[model] = tower
	local prompt = Instance.new("ProximityPrompt")
	prompt.Name = "Upgrade"
	prompt.RequiresLineOfSight = false
	labelPrompt(prompt, tower)
	prompt.Parent = model.PrimaryPart
end)

distanceToPath measures to the nearest point on each path segment, so set PATH_CLEARANCE to half the path's width plus half a tower. GetPartBoundsInBox with an Include filter on the Towers folder only finds towers, so any result means overlap.

Target enemies with one loop for every tower

One script per tower gets slow and messy fast. A single loop for all towers is easier to debug and much cheaper:

Script
-- Same Script, part 6: one loop aims and fires every tower
local function pickTarget(position, range, mode)
	local best, bestScore = nil, -math.huge
	for _, enemy in enemies do
		local gap = (enemy.model:GetPivot().Position - position).Magnitude
		-- "First" means furthest along the path, "Closest" means nearest the tower
		local score = if mode == "Closest" then -gap else enemy.distance
		if not enemy.dead and gap <= range and score > bestScore then
			best, bestScore = enemy, score
		end
	end
	return best
end

local function hitEnemy(enemy, damage, owner)
	enemy.health -= damage
	if enemy.health <= 0 and not enemy.dead then
		enemy.dead = true
		enemy.model:Destroy()
		local leaderstats = owner.Parent and owner:FindFirstChild("leaderstats")
		if leaderstats then
			leaderstats.Cash.Value += enemy.stats.reward
		end
	end
end

task.spawn(function()
	while true do
		local now = os.clock()
		for model, tower in towers do
			local config = TOWERS[tower.kind]
			local stats = config.levels[tower.level]
			local target = now >= tower.ready and pickTarget(tower.position, stats.range, config.targeting)
			if target then
				tower.ready = now + stats.cooldown
				local aim, pivot = target.model:GetPivot().Position, model:GetPivot().Position
				model:PivotTo(CFrame.lookAt(pivot, Vector3.new(aim.X, pivot.Y, aim.Z)))
				hitEnemy(target, stats.damage, tower.owner)
			end
		end
		task.wait(0.1)
	end
end)

Because every enemy carries its distance, "first" is just the biggest number in range. The ready time handles cooldowns, and the kill reward goes to the tower's owner. Damage and cash never leave the server, the same rule as in a sword combat system.

Add upgrades with a ProximityPrompt

Placed towers already carry an Upgrade prompt, and prompts trigger on the server, so there is no RemoteEvent to secure:

Script
-- Same Script, part 7: the Upgrade prompt on each tower
local ProximityPromptService = game:GetService("ProximityPromptService")

ProximityPromptService.PromptTriggered:Connect(function(prompt, player)
	local tower = towers[prompt:FindFirstAncestorOfClass("Model")]
	if prompt.Name ~= "Upgrade" or not tower or tower.owner ~= player then
		return
	end
	local nextLevel = TOWERS[tower.kind].levels[tower.level + 1]
	local cash = player.leaderstats.Cash
	if nextLevel and cash.Value >= nextLevel.price then
		cash.Value -= nextLevel.price
		tower.level += 1
		labelPrompt(prompt, tower)
	end
end)

The targeting loop reads levels[tower.level] every tick, so an upgrade counts from the next shot. To add a tower type, copy the Archer entry in TOWERS with new numbers and add a model of the same name to TowerModels, or ask Revix to add one, model included, in your map's style.

Keep it fast

Load multiplies: towers times enemies times ticks. Four habits keep servers smooth:

  • One loop, a 0.1 second tick. Towers rarely need to think 60 times a second.
  • Few parts per enemy. Every part of every enemy moves each frame.
  • Effects on the client. Use FireAllClients for arrows and sparks and let clients draw them. Very big games move the enemy models on clients too, while the server keeps the numbers.
  • Test the last wave in a live server. Studio on a fast PC hides lag that phones will feel.

Want a twist on the formula? Start from one of these Roblox game ideas.

Questions

How do you make enemies follow a path in Roblox?

Place numbered parts (1, 2, 3...) along the route in a Waypoints folder. Either move each enemy from the server by how far it has walked along those points, or give it a Humanoid and call MoveTo on each waypoint in turn, waiting for MoveToFinished.

How do towers pick which enemy to shoot?

Each tower looks at the enemies inside its range and picks one by a rule. "First" picks the enemy furthest along the path, which is what most players expect; "Closest" picks the one nearest the tower. Run that check for every tower from one server loop.

How do I stop players placing towers on the path?

Check it on the server. The client only sends which tower and where; the server measures the distance from that spot to every path segment, checks for overlapping towers with GetPartBoundsInBox and takes the cost from its own table before placing anything.

How many enemies can a Roblox tower defense game handle?

It depends on your enemy models and your players' devices, so test your biggest wave in a live server rather than trusting a number. Simple anchored models, one loop for all towers and visual effects drawn on the client let you run far more enemies than one Humanoid and one script each.

Your game is
one sentence away.

Start building free

Free to start. No card needed.