Godot Version
4
Question
Hello, I’ve been following a tutorial to make an enemy to chase the player with a grid based movement. The tutorial is this one 2D Enemy movement in Godot 4 using TileMap & AStarGrid2D (youtube.com), but when I test it for the first time, I noticed that the function get_id_path is returning an empty array so the enemy never moves from the spot, and I’ve been trying to figure out why it does not work but I havent been lucky so far.
Here is the code of the enemy movement:
extends Node2D
@onready var player: Area2D = $"../Player"
@onready var tile_map: TileMap = $"../TileMap32"
@onready var sprite: Sprite2D = $Sprite2D
var astar_grid: AStarGrid2D
var used_cells
var is_moving: bool
func _ready():
position = position.snapped(Vector2.ONE * Global.TILE_SIZE)
position -= Vector2.ONE * (Global.TILE_SIZE / 2)
astar_grid = AStarGrid2D.new()
astar_grid.region = tile_map.get_used_rect()
astar_grid.cell_size = Vector2(32, 32)
astar_grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
astar_grid.update()
var region_size = astar_grid.region.size
var region_position = astar_grid.region.position
for x in region_size.x:
for y in region_size.y:
var tile_position = Vector2i(
x + region_position.x,
y + region_position.y
)
var tile_data = tile_map.get_cell_tile_data(0, tile_position)
if tile_data.get_custom_data("walkable") == true:
astar_grid.set_point_solid(tile_position)
func _process(delta):
if is_moving:
return
move()
func move():
var path = astar_grid.get_id_path(
tile_map.local_to_map(global_position),
tile_map.local_to_map(player.global_position)
)
# After this function the path array is empty. I checked if the positions were not empty or giving any errors and I think they're fine
if path.size() == 1:
return
if path.is_empty():
return
var original_pos = Vector2(global_position)
global_position = tile_map.map_to_local(path[0])
sprite.global_position = original_pos
is_moving = true
func _physics_process(delta):
if is_moving:
sprite.global_position = sprite.global_position.move_toward(global_position, 1)
if sprite.global_position != global_position:
return
is_moving = false