So, I edited some things, I changed it so your dict keys are global coords so you don’t have to convert the Vector2’s you send each time, I placed some comments in your code, but I’ll also make them here. Honestly you didn’t need the var free and occupy just for creating your dictionary, so I personally deleted them.
You were creating keys/values for solid points in your AStarGrid, however it doesn’t seem like those points will ever be changed to not solid, so that was a bit redundant. You already won’t navigate to those points since they are solid, and won’t return a path coord.
The real issue I realized is that you having to add that 16 pixel offset to recalculate your path. That means that your global_position and the map tiles converted global_position won’t be the same.
Why do you need that offset? Be detailed and specific please, it may be possible to eliminate the offset.
extends TileMapLayer
var astar: AStarGrid2D
var tile_position: Vector2i
var occupation: Dictionary = {}
func _ready():
astar = AStarGrid2D.new()
astar.region = get_used_rect()
astar.cell_size = Vector2(32, 32)
astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
astar.update()
for x in get_used_rect().size.x:
for y in get_used_rect().size.y:
tile_position = Vector2i(
x + get_used_rect().position.x,
y + get_used_rect().position.y
)
var tile_data = get_cell_tile_data(tile_position)
if tile_position == null or tile_data.get_custom_data("Walkable") == false:
astar.set_point_solid(tile_position)
#occupation[to_global(map_to_local(tile_position))] = true This is unnecessary unless these points can become not solid
else:
occupation[to_global(map_to_local(tile_position))] = false
func find_path(start, end) -> Array:
var id_path = astar.get_point_path(
local_to_map(to_local(start)),
local_to_map(to_local(end))
)
#for i in id_path.size():
#This here is now going to cause you issues with calculating, why do you need this offset?
#id_path[i] = id_path[i] + Vector2(16, 16)
return id_path
func set_occupied(free: Vector2, occupy: Vector2):
occupation[free] = false
occupation[occupy] = true
func check_occupied(point: Vector2) -> bool:
return occupation[point]