When you create tiles you can assign a name and godot automatically assigns each tile created starting from scratch. Through gdscript you can access each tile through its name or ID. Here are some examples:
extends Node2D
onready var tilemap=$TileMap #the child tilemap
onready var tileset= tilemap.tile_set #the tileset of tilemap
var tile_types = {}
var resources = {}
func _ready():
randomize()
#save the tiles ids and names in a dictionary, see the function declaration
tile_types= make_dic_tiles()
for i in tile_types:
print("Tile dictionary keys: ", i) #print keys
for i in tile_types.values():
print("Tile dictionary values: ", i) #...values
#print array of all tiles id:
print("Tile IDs: ", tileset.get_tiles_ids())
#print id for name tile (-1 if no exist):
print("Name tile if exist: ", tileset.find_tile_by_name("castle"))
#print all names your tiles:
for i in tileset.get_tiles_ids():
print("Tiles names: ", tileset.tile_get_name(i))
#print total tiles
var total_tiles=tileset.get_tiles_ids().size()
print("Total tiles: ", total_tiles)
#print size tiles: 16x16, 16x32, etc:
for i in tileset.get_tiles_ids():
print(tileset.tile_get_region(i).size)
print (region_to_tiles(tileset.tile_get_region(i).size))
#example:
random_fill(25,25,20,20,tile_types)
func _process(delta):
#example: delete tiles using mouse. Using (world_to_map) convert global position to tile position
if Input.is_mouse_button_pressed(BUTTON_LEFT):
var x_t=tilemap.world_to_map (get_local_mouse_position()).x
var y_t=tilemap.world_to_map (get_local_mouse_position()).y
# -1 no tile:
tilemap.set_cell( x_t, y_t, -1)
#example: get tile id whit the mouse position:
if Input.is_mouse_button_pressed(BUTTON_RIGHT):
#if Input.is_action_just_pressed("right_mouse_click"):
var tilepos=tilemap.world_to_map (get_local_mouse_position())
print(tilepos)
print(tilemap.get_cell(tilepos.x, tilepos.y))
func make_dic_tiles(): #return dictionary all tiles {tileID, tileName}
var temp_dict={}
for i in tileset.get_tiles_ids().size():
temp_dict[tileset.get_tiles_ids()[i]] = tileset.tile_get_name(i)
return temp_dict
#x and y= count tiles to start (no real position): (Alternative: use world_to_map)
#the tiles can measure more than cell size, this function does not take that into account:
func random_fill(x, y, width:int, heigth:int, tiles:Dictionary) -> void:
for i in width:
for j in heigth:
#random int number...0 to total tiles id
var rnd=randi() % tiles.size()
tilemap.set_cell(i, j, tiles.keys()[rnd])
pass
# if tile is 16x16 return 1,1, 32x16 return 1,2, etc:
func region_to_tiles(tile_size):
return Vector2(1 / tilemap.cell_size.x * tile_size.x, 1 / tilemap.cell_size.y * tile_size.y)
func make_sector(resource):
#...
pass
func make_chunk(size):
#...
pass
#etc
You can also create dictionaries or array of properties according to the name or id of the tile. I also saw that a script can be assigned directly to each tile, but I don't know how it is handled. There are several things to learn ...