Random Item Generation on tilemap

Godot Version

4.2.2

Question

I have a basic tilemap that i want to spawn some collectables on another layer on top of them
i want to check the atlas cords to spawn these collectables on top
for example
if Tilemap.AtlasCord == (6,2):
Scene.Instantiate()

How can i check for the all the atlas cords on the used tiles of the tilemap and instantiate my collectable scenes on random locations of the same atlas cord

instead of using atlas coordinates i use custom data of “wall” because enemy or any collectible wont spawn in a wall. if you wished to spawn a collectible only on specific tile, then in your specific tile, add a custom data layer with certain value then incorporate the masking with it:

here is a script i try to spawn enemy in a TileMap:

func spawn_enemies():
	var all_tilemap_cells = tilemap_node.get_used_cells(0)
	var all_tilemap_cells_masked = [] 
	for i in all_tilemap_cells:
		var tile_world_position = to_global(tilemap_node.map_to_local(i))
		var tile_data=tilemap_node.get_cell_tile_data(1,i)
		player=get_tree().get_nodes_in_group("player")[0]
		if tile_data and tile_data.get_custom_data_by_layer_id(0)=="wall":
			continue
		if player.global_position.distance_to(tile_world_position) > player_mask_radius:
			all_tilemap_cells_masked.append(i)

	if not all_tilemap_cells_masked.is_empty():
		all_tilemap_cells_masked.shuffle()
		for i in enemy_count:
			var tile_world_position = to_global(tilemap_node.map_to_local(all_tilemap_cells_masked[i]))
			var new_enemy = enemy_scene.instantiate()
			add_child(new_enemy)
			new_enemy.global_position = tile_world_position

this should get you some insights how to spawn your collectable

here’s what i mean incorporate the masking with it:
replace it to:

		if tile_data and tile_data.get_custom_data_by_layer_id(0)!="wall" and  tile_data.get_custom_data_by_layer_id(0)=="collectible_tile":
			all_tilemap_cells_masked.append(i)
			
1 Like

thank you so very much
you’ve saved me hours of searching and testing

1 Like