How can I develop interactive tiles that have specific properties?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By joh78-boys

Hello,

I am new to game development but have had prior experience with programs such as Processing and using games made with the software to change it up for practice on coding.

Currently, I am trying to make a game where the maps will have square tiles that are interactive, and the basic thing I need to resolve is making reproducible tiles where the player clicks on a specific tile(say the tile/sprite is black and all the others are white) and then when it clicks on another tile that is not the same as the one it clicked on(such as a tile that is white) it turns that tile black and the one that was previously black, white.

I also wanted to know if I could incorporate these properties into a tilemap so I can get that reproducible and easy placement property for the tiles on a scene.

Thank you.

:bust_in_silhouette: Reply From: Zylann

You can modify tiles in a TileMap, but each tile doesn’t have more information than their ID. So if you want cells to change, you can set a different tile ID.
Here is an example of how you can interact:

extends Node

onready var _tilemap : TileMap = get_node("Tilemap")


func _input(event):
	if event is InputEventMouseButton:
		if event.button_index == BUTTON_LEFT:
			if event.pressed:

				# Get which tile is under the mouse
				var mouse_pos = _tilemap.get_local_mouse_position()
				var cell_pos = _tilemap.world_to_map(mouse_pos)
				var tile_id = _tilemap.get_cellv(cell_pos)
				var tile_name = _tilemap.tile_set.tile_get_name(tile_id)

				# Do stuff according to the above
				if tile_name == "white":
					# For example, turn the tile into a black tile when clicked
					var black_tile_id = _tilemap.tile_set.find_tile_by_name("black")
					_tilemap.set_cellv(cell_pos, black_tile_id)

For more complex behavior, usually people go around that by overlaying actual nodes over their tilemap (sprites, particles…) or storing extra states in a dictionary indexed by tile position.