Astar_Grid initialization code doesn't work in ready() funtion

Godot Version

4.2.1 Stable

Question

My Astar_Grid initialization code only works when put in the _input() function. When put in the ready() function the code just won’t work and when I try to call get_id_path() in the input() function it only returns an error:
Map.gd:39 @ _input(): Can’t get id path. Point(5, 3) out of bounds [P:(0, 0), S:(0, 0)]
But if I put the Astar_Grid initialization code in the _input()function everything works just fine. Why?

Astar_Grid initialization code:

	astar_grid = AStarGrid2D.new()
	astar_grid.region = get_used_rect()
	astar_grid.cell_size = Vector2(96, 96)
	astar_grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER  
	astar_grid.update()
	print("Astar grid initialization complete")

My _input() function:

func _input(_event):
	var tile_click_position:Vector2
	var click_position:Vector2

	
	#generate the array which stores player's mouse click
	if Input.is_action_just_pressed("click"):
		click_position = to_local(get_global_mouse_position())
		tile_click_position = local_to_map(click_position)
		if mouse_click_array.size()<2:
			mouse_click_array.append(tile_click_position)
		else:
			mouse_click_array[0] = mouse_click_array[1]
			mouse_click_array[1] = tile_click_position
		print(mouse_click_array, "was chosen")
		
		#calculate if an available path exists for the 2 vectors:
		if mouse_click_array.size() == 2:
			if mouse_click_array[0] != mouse_click_array[1]:
				#decide whether the 2 items in the array display the same kind of food
				var id1 = get_cell_atlas_coords(0, mouse_click_array[0])
				var id2 = get_cell_atlas_coords(0, mouse_click_array[1])
				if id1 == id2:
					#find is there a potential available path between the two tiles
					var connect_path = astar_grid.get_id_path(mouse_click_array[0], mouse_click_array[1])
					print("The path is", connect_path)
					
					
					
					if true:
						set_cell(0, mouse_click_array[0], -1)
						set_cell(0, mouse_click_array[1], -1)
						
					else:    #else for no available path found between the two identical tiles
						pass
						
			else:    #else for the same tile click twice and nothing happens
				pass


	else:    #else for if no input
		pass
	return    #end this func

Problem solved! Turns out at the time the _input() function is called, the Astar_Grid has not been fully initialized or updated.
So I add a new global value initialization_flag set false by default, and can only be set true when the initialization is fully completed, and only by which the code following can be executed.

call_deferred() is often an easy to fix this

extends Node2D

func message(a_message):
	print(a_message)
	
func add(a_num_1, a_num_2):
	print(a_num_1 + a_num_2)
	
func _ready():
	call_deferred("message", "I just did something!")
	call_deferred("add", 5, 10)

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.