Pathfinding with procedural generation - semiworking

Godot Version

4.2

Question

Currently, paths are being drawn towards the player, however, they are straight and go through the tiles. I have done this through code, which is why I am confused.

Code:

extends Node2D

var borders = Rect2(1, 1, 152, 82)

signal player_location(spawn_position)
@onready var tileMap = $TileMap
const Spawner = preload("res://enemy_spawner.tscn")
 
var navigation_mesh: NavigationPolygon
var region_rid: RID

func _ready():
	randomize()
	navigation_mesh = NavigationPolygon.new()
	region_rid = NavigationServer2D.region_create()
	generate_level()

func generate_level():
	var walker = Walker.new(Vector2(76, 41), borders)
	var map = walker.walk(1000)
	
	for location in map:
		tileMap.erase_cell(0, location)
	
	var player_position = map.front() * 16 
	set_player_spawn(player_position)
	
	var spawner = Spawner.instantiate()
	add_child(spawner)
	spawner.position = walker.get_end_room().position * 16
	
	walker.queue_free()
		
	var used_tiles = tileMap.get_used_cells(0)
	for tile in used_tiles:
		tileMap.erase_cell(0, tile)
		
	setup_navigation_mesh(map)
	
	tileMap.set_cells_terrain_connect(0, used_tiles, 0, 0)
	
	
func setup_navigation_mesh(map):
	# Create navigation mesh vertices based on the walker path
	var vertices := PackedVector2Array()
	var indices := PackedInt32Array()
	
	# Generate vertices from the procedural map data
	var index = 0
	for location in map:
		var position = location * 16  # Assuming tile size is 16x16
		vertices.append(position)
		indices.append(index)
		index += 1
	
	# Set the vertices for the navigation mesh
	navigation_mesh.vertices = vertices
	navigation_mesh.add_polygon(indices)

	# Set the navigation region with the created navigation mesh
	NavigationServer2D.region_set_enabled(region_rid, true)
	NavigationServer2D.region_set_map(region_rid, get_world_2d().get_navigation_map())
	NavigationServer2D.region_set_navigation_polygon(region_rid, navigation_mesh)

There is information missing that is crucial to your problem. What does the Walker class look like and what is returned by walker.walk(1000). I’m assuming it’s an array filled with Vector2 positions?

You say the path goes trough the tiles, but what does that mean? Are some tiles supposed to be walls where the path should go around?

Without knowing how the map variable is created and what is contained in it, it will be difficult to say much.

I have solved it, was much easier than I thought. All you had to do was place a navigationregion2d manually, and then once your tilemap is created, bake the region.