Day 4: This Kinda Looks Like a Game

[Tower Defense]


Tutorials done, mining game abandoned. I thought a tower defense could be a good place to start, not too complicated?

Yesterday I watched a tilemap tutorial by ThinkWithGames. Current goal: just get tiles rendering on screen, layers, tiles, the basics.

Got it working. Cool. Now, let’s place a dude on there.

Enemy sprite placed on the tilemap

Wow, there’s a dude on a map! Does it do anything? C’mon, buddy, do something.

AStarGrid2D just… exists

Turns out Godot has built-in grid pathfinding. You don’t import a library, you don’t write your own algo, it’s just there, thanks Godot! Set up a region, tell it your cell size, and ask for a path:

var astar = AStarGrid2D.new()
astar.region = Rect2i(0, 0, 15, 17)
astar.cell_size = Vector2(16, 16)
astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
astar.update()

# Returns list of Vector2i, e.g. [(0,1), (1,1), (2,1)]
var path = astar.get_id_path(enemy.grid_pos, goal)
# Returns the same list, but in Vector2.
var path = astar.get_point_path(enemy.grid_pos, goal)

I just grab the next entry in the returned list and set it to be little buddy’s position. The dude walks toward the goal. Well, kinda. There’s no animation or anything. No obstacles yet, just a straight-ish path across the grid.

Enemy navigating toward the goal

Next: paint some obstacle tiles onto the map and tell A* about them:

for cell in obstacles_layer.get_used_cells():
    astar.set_point_solid(cell)

Now the dude routes around them! Wow, look at em go!

Enemy routing around obstacles with a piece in the tray

Godot’s Navigation docs have all sorts of useful links, check it out.

I kept going. Made a PieceDef resource to define piece shapes:

class_name PieceDef
extends Resource

@export var piece_name: String
@export var offsets: Array[Vector2i]
@export var color: Color

An L-shaped piece is just offsets = [(0,0), (0,1), (0,2), (1,2)]. I can define new shapes in the editor.

Built a tray UI to hold the piece (there’s only 1 now and it doesn’t do anything), and by the end of the session I had: a tilemap, an enemy that pathfinds, and one L-shaped (actually J, but, it’s ok) piece sitting in a tray waiting to be placed.

I’d been thinking of building a tower defense game for a bit. Enemies on a tilemap, some obstacles, pathfinding around obstacles…I just need attack mechanics and that’s most of the core. Getting an enemy moving on a tilemap around obstacles, this feels real, this is buildable, maybe.


Sprites from kenney.nl.