[hopefully an informative late reply for anyone inquiring the same, like I did]
I’m not using a TileMap and I implemented a simple solution using a built-in Godot’s AStarGrid2D object.
I just followed the first example you find in its Godot Docs page:
Documentation for AStarGrid2D class
Basically, all you need to do to set it up is:
var astar_grid = AStarGrid2D.new() # instantiates the AStarGrid2D object
astar_grid.region = Rect2i(0, 0, your_grid_width, your_grid_height) # defines the size of the navigatable grid
astar_grid.cell_size = Vector2(your_cell_width, your_cell_height) # defines the size of the navigatable grid's cell size
astar_grid.update() # updates the AStarGrid2D object with new grid parameters
To get a calculated path between 2 positions, just add:
var id_path = astar_grid.get_id_path(starting_position, destination_position)
# get_id_path() returns an array of Vector2i, with each element being the next valid cell position.
· The first element of the array will always be the starting position.
If you want to exclude the starting position, you may instead:
var id_path = astar_grid.get_id_path(starting_position, destination_position).slice(1)
Additionally:
astar_grid.set_point_solid(Vector2i(cell_x, cell_y)) # sets the cell as 'solid' (blocked/not navigatable/impassable)
astar_grid.update() # needs to be called every time you change the AStarGrid2D grid parameters
An example of code:
@export var grid_width: int
@export var grid_height: int
@export var tile_width: int
@export var tile_height: int
var id_path
func _ready():
setup_astar_grid_2d()
func _physics_process(delta):
if id_path:
navigate_path()
func setup_astar_grid_2d():
astar_grid = AStarGrid2D.new()
astar_grid.region = Rect2i(0, 0, grid_width, grid_height)
astar_grid.cell_size = Vector2(tile_width, tile_height)
astar_grid.default_compute_heuristic = AStarGrid2D.HEURISTIC_OCTILE
astar_grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_ONLY_IF_NO_OBSTACLES
astar_grid.update()
func get_path(current_position: Vector2i, target_position: Vector2i):
id_path = astar_grid.get_id_path(current_position, target_position)