1. What We're Building
This tutorial walks through a complete, working tower defense game for Godot 4.6, written in GDScript 2.0. It is not pseudo-code: every excerpt below is copied from the real project's scripts, and only indentation was changed for the web. The project has five small scripts:
main.gd— the grid, the path, waves, tower placement, the economy and the HUD;enemy.gd— a jelly blob that walks the path and can be damaged;tower.gd— a turret that aims at a target and fires on a cooldown;bullet.gd— a homing projectile, with optional splash damage;fx.gd— confetti bursts, rings and floating “+10” text.
The scene tree is tiny: a Main Node2D with four empty Node2D containers (Towers, Enemies, Bullets, FX) and a HUD CanvasLayer holding three labels, three buttons and a banner label. Enemies, towers and bullets are plain Node2Ds created from scripts at runtime, and everything is drawn with _draw(), so there are no image assets at all.
2. The Grid and the Waypoint Path
The map is a 20×10 grid of 64-pixel tiles, pushed down 80 pixels to leave room for the HUD bar. That is exactly 1280×720, the project's viewport size. The enemy path is not a list of every tile; it is a short list of waypoints where the path turns:
const TILE := 64
const TOP := 80
const COLS := 20
const ROWS := 10
const WAYPOINTS := [Vector2i(-1, 2), Vector2i(4, 2), Vector2i(4, 7), Vector2i(9, 7), Vector2i(9, 1), Vector2i(14, 1), Vector2i(14, 8), Vector2i(20, 8)]
Note the first and last waypoints: (-1, 2) and (20, 8) are one cell outside the grid, so enemies walk in from off-screen on the left and leave off-screen on the right. Two helpers convert between grid cells and pixels:
func cell_center(c: Vector2i) -> Vector2:
return Vector2(c.x * TILE + TILE * 0.5, TOP + c.y * TILE + TILE * 0.5)
func pos_to_cell(p: Vector2) -> Vector2i:
if p.y < TOP:
return Vector2i(-100, -100)
return Vector2i(floori(p.x / TILE), floori((p.y - TOP) / TILE))
pos_to_cell() returns an impossible cell for clicks on the HUD bar, so those can never place a tower. In _ready(), the waypoints become two things: a PackedVector2Array of pixel positions for enemies to walk, and a dictionary of every cell the path covers, built by stepping one cell at a time from each waypoint to the next:
for wp in WAYPOINTS:
path_points.append(cell_center(wp))
for i in range(WAYPOINTS.size() - 1):
var a: Vector2i = WAYPOINTS[i]
var b: Vector2i = WAYPOINTS[i + 1]
var step := Vector2i(signi(b.x - a.x), signi(b.y - a.y))
var c := a
path_cells[c] = true
while c != b:
c += step
path_cells[c] = true
Because every segment is horizontal or vertical, signi() gives a unit step such as (1, 0) or (0, -1). path_cells is used as a set: the tower placement rules only ask path_cells.has(c).
3. Drawing the Map with _draw()
main.gd calls queue_redraw() at the end of every _process(), and its _draw() paints the whole map: a two-tone grass checkerboard, little animated flowers, the path, a beating heart at the exit, the placement preview and the top bar. The path is the neat part. A thick draw_polyline() gives straight segments, and a circle at every waypoint rounds off the corners. Doing it twice, dark and wide then light and narrow, gives the path an outline:
draw_polyline(path_points, Color("e8a95c"), 60.0)
for p in path_points:
draw_circle(p, 30.0, Color("e8a95c"))
draw_polyline(path_points, Color("ffe3a3"), 48.0)
for p in path_points:
draw_circle(p, 24.0, Color("ffe3a3"))
After that, a loop walks the segments and draws small dots offset by time * 40.0, so the path appears to march toward the exit, a cheap hint of which way enemies will go.
4. Enemies That Follow the Path
Many Godot tower defense tutorials reach for Path2D and PathFollow2D. This project does it by hand, which is only a few lines. Each enemy gets the path array and an index idx of the waypoint it is heading to. Every frame it has a movement budget of speed * delta pixels and spends it walking toward the next point. If it reaches a waypoint with budget left over, it keeps going toward the following one, so enemies never stall or cut corners on fast frames:
var move := speed * delta
while move > 0.0 and idx < path.size():
var target := path[idx]
var d := position.distance_to(target)
if d <= move:
position = target
move -= d
progress += d
idx += 1
else:
dir = (target - position).normalized()
position += dir * move
progress += move
move = 0.0
if idx >= path.size():
reached_end.emit(self)
queue_free()
return
Two details matter later. progress is the total distance walked, which towers use to decide who to shoot. dir is the current walking direction, which the enemy's _draw() uses to make its eyes look where it is going. The enemy reports back to main.gd with two signals, died and reached_end, rather than touching the game state itself:
func take_damage(amount: float) -> void:
if hp <= 0.0:
return
hp -= amount
hit_flash = 1.0
if hp <= 0.0:
died.emit(self)
queue_free()
The early return stops an enemy from dying twice when several bullets hit it in the same frame, which would otherwise pay out its reward twice. hit_flash briefly lerps the body color toward white, and a green health bar appears above the blob once it has taken damage.
5. Tower Placement on the Grid
The placement rule is four conditions: the cell is on the grid, it is not part of the path, it does not already hold a tower, and you can afford the selected tower. main.gd spells this out in a helper:
func can_place(c: Vector2i) -> bool:
var t: Dictionary = TOWERS[selected]
return in_bounds(c) and not path_cells.has(c) and not tower_cells.has(c) and coins >= t["cost"]
The actual click handler, _try_place(), runs the same checks one at a time, because it wants to react differently to each: a click on the path is silently ignored, but a click you can't afford shows a floating “Need $50”. If everything passes, it pays, creates the tower from its script, copies the stats in and records the cell:
if coins < t["cost"]:
fx.float_text(cell_center(c), "Need $%d" % t["cost"], Color("ff5c8a"))
return
coins -= t["cost"]
var tw = TowerScript.new()
tw.main = self
tw.position = cell_center(c)
tw.range_px = t["range"]
tw.fire_rate = t["rate"]
tw.damage = t["damage"]
tw.splash = t["splash"]
tw.color = t["color"]
towers.add_child(tw)
tower_cells[c] = tw
The placement preview lives in _draw(). _unhandled_input() stores the hovered cell on every mouse motion, and the preview draws a white square over it when placement is allowed or a red one when it isn't, plus the tower's range circle whenever the cell is free:
var free := not path_cells.has(hover_cell) and not tower_cells.has(hover_cell)
var ok: bool = free and coins >= int(t["cost"])
var col := Color(1, 1, 1, 0.45) if ok else Color(1, 0.2, 0.35, 0.4)
draw_rect(Rect2(center - Vector2(28, 28), Vector2(56, 56)), col)
if free:
draw_circle(center, t["range"], Color(1, 1, 1, 0.12))
draw_arc(center, t["range"], 0.0, TAU, 64, Color(1, 1, 1, 0.7), 3.0)
Showing the range even when you can't afford the tower is a nice touch: you can plan your next placement while you wait for coins.
6. Two Tower Types and Targeting
Tower stats are data, not code. A constant array of dictionaries defines both towers, and one tower.gd script serves both:
const TOWERS := [
{"name": "Popper", "cost": 50, "range": 150.0, "rate": 0.35, "damage": 1.0, "splash": 0.0, "color": Color("ff4fa3")},
{"name": "Boomer", "cost": 100, "range": 190.0, "rate": 1.2, "damage": 3.0, "splash": 70.0, "color": Color("ffb703")},
]
The Popper is the cheap, fast single-target tower: it fires every 0.35 seconds for 1 damage. The Boomer costs twice as much and fires only every 1.2 seconds, but for 3 damage to everything within 70 pixels of the impact. That is the classic trade-off: Poppers are efficient against a thin stream of enemies, Boomers against crowds. You pick one with the HUD buttons or with the 1 and 2 keys.
Targeting lives in main.gd, because that is the node that knows about all enemies. Of every live enemy within range, find_target() returns the one with the highest progress, the one closest to the exit. This “first” rule is what most tower defense games default to:
func find_target(pos: Vector2, r: float) -> Node2D:
var best: Node2D = null
var best_prog := -1.0
for e in enemies.get_children():
if e.is_queued_for_deletion() or e.hp <= 0.0:
continue
if e.position.distance_to(pos) <= r and e.progress > best_prog:
best = e
best_prog = e.progress
return best
Each tower asks for a target every frame, turns its barrel toward it smoothly with lerp_angle(), and fires when its cooldown runs out. The bullet spawns at the tip of the barrel, 30 pixels out along the aim direction:
var target: Node2D = main.find_target(position, range_px)
if target:
var want := (target.position - position).angle()
aim = lerp_angle(aim, want, minf(1.0, delta * 18.0))
if cooldown <= 0.0:
cooldown = fire_rate
recoil = 1.0
main.spawn_bullet(position + Vector2.from_angle(aim) * 30.0, target, damage, splash, color)
Asking every frame is fine at this scale: with a few dozen towers and enemies it is a few hundred distance checks. If you build a game with hundreds of each, an Area2D per tower or a spatial grid would be the next step. In _draw(), the tower pops in with an ease-out-back scale, its barrel kicks back with recoil, and the splash tower gets a thicker barrel and a little star.
7. Bullets and Splash Damage
Bullets home in on their target but remember its last position. If the target dies mid-flight, the bullet keeps flying to the spot where it was last seen instead of vanishing or crashing on a freed node:
if is_instance_valid(target) and not target.is_queued_for_deletion():
target_pos = target.position
var to := target_pos - position
if to.length() <= speed * delta:
position = target_pos
_hit()
return
position += to.normalized() * speed * delta
On impact, a single-target bullet damages only its target. A splash bullet hands off to main.gd, which damages every enemy whose body overlaps the blast circle. Adding e.radius to the range makes big enemies easier to catch at the edge, which feels right:
func _hit() -> void:
if splash > 0.0:
main.splash_damage(position, splash, damage)
main.fx.burst(position, color, 1.6, splash)
else:
if is_instance_valid(target) and not target.is_queued_for_deletion():
target.take_damage(damage)
main.fx.burst(position, color, 0.5, 18.0)
queue_free()
func splash_damage(pos: Vector2, r: float, dmg: float) -> void:
for e in enemies.get_children():
if not e.is_queued_for_deletion() and e.position.distance_to(pos) <= r + e.radius:
e.take_damage(dmg)
The fx.burst() call draws an expanding ring the size of the splash radius, so the player can see exactly what the Boomer hit.
8. Waves, Scaling and Tank Enemies
Waves start when you press Start Wave (or Space). Each wave has two more enemies than the last:
func start_wave() -> void:
if wave_active or game_over:
return
wave += 1
to_spawn = 6 + wave * 2
spawned = 0
spawn_timer = 0.0
wave_active = true
_show_banner("Wave %d!" % wave)
_update_hud()
Every spawned enemy gets more HP and speed as the wave number climbs. From wave 3 on, every fifth enemy is a tank: bigger, with triple HP, 60% speed and a 25-coin reward instead of 10. Tanks are what make the splash tower worth its price, since the slow tank bunches the regular blobs up behind it:
var e = EnemyScript.new()
var hp := 3.0 + wave * 1.5
e.path = path_points
e.position = path_points[0]
e.speed = 80.0 + wave * 6.0
e.color = ENEMY_COLORS[spawned % ENEMY_COLORS.size()]
if wave >= 3 and spawned % 5 == 4:
e.radius = 26.0
hp *= 3.0
e.speed *= 0.6
e.reward = 25
The spawn loop runs in _process(). The gap between spawns shrinks with each wave, but never below 0.35 seconds. When nothing is left to spawn and no enemy is alive, the wave ends and pays a bonus:
if wave_active and not game_over:
spawn_timer -= delta
if to_spawn > 0 and spawn_timer <= 0.0:
_spawn_enemy()
to_spawn -= 1
spawn_timer = maxf(0.35, 0.8 - wave * 0.03)
if to_spawn == 0 and _alive_enemies() == 0:
wave_active = false
var bonus := 20 + wave * 5
coins += bonus
_show_banner("Wave %d cleared! +%d" % [wave, bonus])
_update_hud()
_alive_enemies() skips nodes that are already queued for deletion. A node freed with queue_free() stays in the tree until the end of the frame, so without that check an enemy that just died would still be counted.
All the difficulty lives in a handful of numbers: 6 + wave * 2 enemies, 3.0 + wave * 1.5 HP, 80.0 + wave * 6.0 speed, the tank rule and the costs in TOWERS. Change those first when balancing.
9. Coins, Lives, Game Over and the HUD
You start with 150 coins and 20 lives. A kill pays the enemy's reward through the died signal; an enemy reaching the heart costs one life through reached_end. When lives hit zero, the game freezes the action by disabling processing on the three gameplay containers, a simple way to pause everything without pausing the HUD or the banner animation:
if lives <= 0:
lives = 0
game_over = true
wave_active = false
enemies.process_mode = Node.PROCESS_MODE_DISABLED
towers.process_mode = Node.PROCESS_MODE_DISABLED
bullets.process_mode = Node.PROCESS_MODE_DISABLED
_show_banner("GAME OVER\nClick to try again", 9999.0)
_update_hud()
Restarting is one line. In _unhandled_input(), any left click after game over reloads the scene, which resets every variable for free:
if game_over:
get_tree().reload_current_scene()
return
The HUD is ordinary Label and Button nodes on a CanvasLayer, styled entirely from code with StyleBoxFlat overrides (rounded corners, a thick bottom border for a chunky “candy” look, a white border on the selected tower). One function refreshes it after anything changes:
func _update_hud() -> void:
coins_label.text = "$ %d" % coins
lives_label.text = "Lives %d" % lives
wave_label.text = "Wave %d" % wave
start_btn.disabled = wave_active or game_over
start_btn.text = "Wave running..." if wave_active else "Start Wave"
Disabling the Start button during a wave is the whole “build phase / fight phase” system: you can still place towers mid-wave, but you can't stack waves on top of each other.
10. Building It with AI
You can type all of this in yourself. But this game was not written by hand. It was built by Claude Code connected to the Godot editor through Godot MCP Pro, from this single prompt:
The build took about five minutes. Because MCP lets the AI run the game, click, and take screenshots, it play-tested its own work and fixed two bugs nobody pointed out:
- The window cut off the right edge of the map. The fix was a project setting: the stretch mode is now
canvas_itemswith a 1280×720 viewport, so the 20×64-pixel grid always fits the window. - The GAME OVER banner was invisible. The banner's pop-in animation scaled it far too large. The game-over banner is shown with a duration of
9999.0seconds, so an animation driven by the remaining time blows up. The final code keeps two timers:banner_time(remaining, used for the fade) andbanner_age(elapsed since shown, used for the pop-in), so the banner starts 1.45× large and settles to normal size in 0.3 seconds whatever its duration.
if banner_time > 0.0:
banner_time -= delta
banner_age += delta
banner.modulate.a = clampf(banner_time * 2.0, 0.0, 1.0)
banner.scale = Vector2.ONE * (1.0 + maxf(0.0, 0.3 - banner_age) * 1.5)
You can watch the whole build, unedited, on YouTube, and see the prompt and details on the Pop Tower Defense showcase page. Godot MCP Pro gives an AI assistant 190 editor and runtime tools — create scenes and scripts, change project settings, run the game, simulate mouse clicks and key presses, capture screenshots and read errors — so it can do the same edit, run, look, fix loop you'd do by hand. It also works on your own project: ask it to add a slowing tower, a sell button or a boss wave, and it can play the result to check it.
11. FAQ
Should I use Path2D and PathFollow2D for tower defense enemies in Godot 4?
You can, but you don't have to. This tutorial stores the path as a PackedVector2Array of waypoint centers and moves each enemy toward the next point by speed * delta, carrying any leftover distance into the next segment. It also adds up the distance walked in a progress variable, which is exactly what tower targeting needs. Path2D with PathFollow2D gives you curves and an editor gizmo, and PathFollow2D.progress plays the same role.
How do I stop players from placing towers on the path?
Keep a dictionary of every grid cell the path passes through, built once by stepping cell by cell between waypoints, and a second dictionary of cells that already hold a tower. A cell is placeable when it is inside the grid, in neither dictionary, and the player has enough coins. The same check colors the hover preview white or red.
Which enemy should a tower shoot first?
The usual rule is “first”: of all enemies in range, pick the one that has walked farthest along the path, because it is closest to leaking a life. The find_target() function in this tutorial does that by comparing each enemy's progress value.
Which Godot version does this code need?
It was written and run on Godot 4.6 in GDScript 2.0. It uses Godot 4 APIs such as queue_redraw(), Vector2i, signal.emit(), lambdas passed to pressed.connect() and MOUSE_BUTTON_LEFT, so it will not run on Godot 3 without changes.
Let AI Build and Play-Test Your Godot Game
Godot MCP Pro connects Claude Code, Cursor, Cline and other AI assistants to the Godot 4 editor with 190 tools: build scenes, write scripts, run the game, simulate input and fix what breaks.
create_script
set_project_setting
play_scene
simulate_mouse_click
get_game_screenshot
One-time purchase · Lifetime updates · See pricing details